From f198cd96b68fa7a40adc3183a1c9b7a7692b0500 Mon Sep 17 00:00:00 2001 From: Alexander Zinchuk Date: Sun, 20 Mar 2022 14:29:08 +0100 Subject: [PATCH] [Build] --- .patch-version | 2 +- ...54.71017c16320a06ddc8da.js => 354.a5e899b2a69f227670ec.js} | 2 +- ...c16320a06ddc8da.js.map => 354.a5e899b2a69f227670ec.js.map} | 2 +- ...24.e3a446e0b4e9c7ce5ef9.js => 524.f47aff24c24945077d39.js} | 2 +- ...6e0b4e9c7ce5ef9.js.map => 524.f47aff24c24945077d39.js.map} | 2 +- ....dfb0d60d06da102bbad4.css => 616.421a1d053cdd90ce3d23.css} | 4 ++-- ...d06da102bbad4.css.map => 616.421a1d053cdd90ce3d23.css.map} | 2 +- ...16.dfb0d60d06da102bbad4.js => 616.421a1d053cdd90ce3d23.js} | 2 +- ...60d06da102bbad4.js.map => 616.421a1d053cdd90ce3d23.js.map} | 2 +- ...42.e09d8d2bec0ce4cf0543.js => 742.b2feed9283c594eb9e2f.js} | 4 ++-- ...d2bec0ce4cf0543.js.map => 742.b2feed9283c594eb9e2f.js.map} | 2 +- dist/index.html | 2 +- ...n.687698a9e9aa68d75d14.js => main.040a86fe9347e4854db9.js} | 4 ++-- ...a9e9aa68d75d14.js.map => main.040a86fe9347e4854db9.js.map} | 2 +- dist/report.html | 4 ++-- 15 files changed, 19 insertions(+), 19 deletions(-) rename dist/{354.71017c16320a06ddc8da.js => 354.a5e899b2a69f227670ec.js} (98%) rename dist/{354.71017c16320a06ddc8da.js.map => 354.a5e899b2a69f227670ec.js.map} (99%) rename dist/{524.e3a446e0b4e9c7ce5ef9.js => 524.f47aff24c24945077d39.js} (99%) rename dist/{524.e3a446e0b4e9c7ce5ef9.js.map => 524.f47aff24c24945077d39.js.map} (99%) rename dist/{616.dfb0d60d06da102bbad4.css => 616.421a1d053cdd90ce3d23.css} (93%) rename dist/{616.dfb0d60d06da102bbad4.css.map => 616.421a1d053cdd90ce3d23.css.map} (88%) rename dist/{616.dfb0d60d06da102bbad4.js => 616.421a1d053cdd90ce3d23.js} (99%) rename dist/{616.dfb0d60d06da102bbad4.js.map => 616.421a1d053cdd90ce3d23.js.map} (99%) rename dist/{742.e09d8d2bec0ce4cf0543.js => 742.b2feed9283c594eb9e2f.js} (99%) rename dist/{742.e09d8d2bec0ce4cf0543.js.map => 742.b2feed9283c594eb9e2f.js.map} (99%) rename dist/{main.687698a9e9aa68d75d14.js => main.040a86fe9347e4854db9.js} (99%) rename dist/{main.687698a9e9aa68d75d14.js.map => main.040a86fe9347e4854db9.js.map} (99%) diff --git a/.patch-version b/.patch-version index d00491fd..0cfbf088 100644 --- a/.patch-version +++ b/.patch-version @@ -1 +1 @@ -1 +2 diff --git a/dist/354.71017c16320a06ddc8da.js b/dist/354.a5e899b2a69f227670ec.js similarity index 98% rename from dist/354.71017c16320a06ddc8da.js rename to dist/354.a5e899b2a69f227670ec.js index 42b5025d..3b9a781b 100644 --- a/dist/354.71017c16320a06ddc8da.js +++ b/dist/354.a5e899b2a69f227670ec.js @@ -1,2 +1,2 @@ (()=>{"use strict";var e,r,t={2993:(e,r,t)=>{var n=t(5802);"undefined"!=typeof window&&window.innerHeight,Math.round(425),new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]);const a=new Set(["image/png","image/gif","image/jpeg"]),o=new Set(["video/mp4"]);new Set([...a,...o]),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),i({type:"unhandledError",error:{message:e.error.message||"Uncaught exception in worker"}})},self.addEventListener("unhandledrejection",(e=>{console.error(e),i({type:"unhandledError",error:{message:e.reason.message||"Uncaught rejection in worker"}})}));const s=new Map;function i(e,r){r?postMessage(e,r):postMessage(e)}let c;self.importScripts("rlottie-wasm.js");const l=new Promise((e=>{Module.onRuntimeInitialized=()=>{c={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()}})),d=new Map;async function u(e){const r=await fetch(e),t=r.headers.get("Content-Type");if(null!=t&&t.startsWith("text/"))return r.text();const a=await r.arrayBuffer();return(0,n.inflate)(a,{to:"string"})}function m(e,r,t){const n=r?30:60,a=JSON.parse(e).fr||n,o=a%n==0?a/n:1;return{reduceFactor:o,msPerFrame:1e3/(a/o),reducedFramesCount:Math.ceil(t/o)}}var p;p={init:async function(e,r,t,n,a){c||await l;const o=await u(r),s=allocate(intArrayFromString(o),"i8",0),i=c.init(),p=c.loadFromData(i,s);c.resize(i,t,t);const{reduceFactor:g,msPerFrame:f,reducedFramesCount:h}=m(o,n,p);d.set(e,{imgSize:t,reduceFactor:g,handle:i}),a(g,f,h)},changeData:async function(e,r,t,n){c||await l;const a=await u(r),o=allocate(intArrayFromString(a),"i8",0),{handle:s}=d.get(e),i=c.loadFromData(s,o),{reduceFactor:p,msPerFrame:g,reducedFramesCount:f}=m(a,t,i);n(p,g,f)},renderFrames:async function(e,r,t,n){c||await l;const{imgSize:a,reduceFactor:o,handle:s}=d.get(e);for(let e=r;e<=t;e++){const r=e*o;c.render(s,r);const t=c.buffer(s),i=Module.HEAPU8.subarray(t,t+a*a*4);n(e,new Uint8ClampedArray(i).buffer)}},destroy:function(e){const r=d.get(e);c.destroy(r.handle),d.delete(e)}},onmessage=async e=>{const{data:r}=e;switch(r.type){case"callMethod":{const{messageId:e,name:t,args:n}=r;try{if(e){const r=function(){for(var r=arguments.length,t=new Array(r),n=0;n{var e=a.O(void 0,[802],(()=>a(2993)));return a.O(e)},e=[],a.O=(r,t,n,o)=>{if(!t){var s=1/0;for(d=0;d=o)&&Object.keys(a.O).every((e=>a.O[e](t[c])))?t.splice(c--,1):(i=!1,o0&&e[d-1][2]>o;d--)e[d]=e[d-1];e[d]=[t,n,o]},a.f={},a.e=e=>Promise.all(Object.keys(a.f).reduce(((r,t)=>(a.f[t](e,r),r)),[])),a.u=e=>e+".acd83f1b28a8893b9dba.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,r)=>Object.prototype.hasOwnProperty.call(e,r),(()=>{var e;a.g.importScripts&&(e=a.g.location+"");var r=a.g.document;if(!e&&r&&(r.currentScript&&(e=r.currentScript.src),!e)){var t=r.getElementsByTagName("script");t.length&&(e=t[t.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={354:1};a.f.i=(r,t)=>{e[r]||importScripts(a.p+a.u(r))};var r=self.webpackChunktelegram_t=self.webpackChunktelegram_t||[],t=r.push.bind(r);r.push=r=>{var[n,o,s]=r;for(var i in o)a.o(o,i)&&(a.m[i]=o[i]);for(s&&s(a);n.length;)e[n.pop()]=1;t(r)}})(),r=a.x,a.x=()=>a.e(802).then(r),a.x()})(); -//# sourceMappingURL=354.71017c16320a06ddc8da.js.map \ No newline at end of file +//# sourceMappingURL=354.a5e899b2a69f227670ec.js.map \ No newline at end of file diff --git a/dist/354.71017c16320a06ddc8da.js.map b/dist/354.a5e899b2a69f227670ec.js.map similarity index 99% rename from dist/354.71017c16320a06ddc8da.js.map rename to dist/354.a5e899b2a69f227670ec.js.map index c84f3a1e..a7207f73 100644 --- a/dist/354.71017c16320a06ddc8da.js.map +++ b/dist/354.a5e899b2a69f227670ec.js.map @@ -1 +1 @@ -{"version":3,"file":"354.71017c16320a06ddc8da.js","mappings":"uBAAIA,ECAAC,E,gCC0CkC,oBAAXC,QAA0BA,OAAOC,YAqEzBC,KAAKC,MAAM,KACJ,IAAIC,IAAI,CAChD,aAAc,sBAAuB,iBAAkB,0BAA2B,kBAjH7E,MA8IMC,EAAgC,I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A,EAAQvD,GACdY,EAASlB,QACdwD,EAAgBtC,EAAS4C,OAAS,EACnCJ,EAA2BnI,K,GXnBxBpB,EAAOmG,EAAoBQ,EAC/BR,EAAoBQ,EAAI,IAChBR,EAAoBzF,EAAE,KAAKkJ,KAAK5J,GYDdmG,EAAoBQ,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/createWorkerInterface.ts","webpack://telegram-t/./src/lib/rlottie/rlottie.worker.ts","webpack://telegram-t/webpack/bootstrap","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/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(802).then(next);\n};","export const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION!;\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 PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const DEBUG_PAYMENT_SMART_GLOCAL = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 500;\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 200;\nexport const GLOBAL_STATE_CACHE_CHATS_WITH_MESSAGES_LIMIT = 30;\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-v8';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const AUTODOWNLOAD_FILESIZE_MB_LIMITS = [1, 5, 10, 50, 100, 500];\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\nexport const GROUP_CALL_PARTICIPANTS_LIMIT = 100;\nexport const REACTION_LIST_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\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\nexport const CUSTOM_APPENDIX_ATTRIBUTE = 'data-has-custom-appendix';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const 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 = 100;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const STICKER_SIZE_JOIN_REQUESTS = 140;\nexport const STICKER_SIZE_INVITES = 140;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const NO_STICKER_SET_ID = 'NO_STICKER_SET';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\nexport const VIDEO_WEBM_TYPE = 'video/webm';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const 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\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: any) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n 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 { inflate } from 'pako/dist/pako_inflate';\nimport 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 HIGH_PRIORITY_MAX_FPS = 60;\nconst LOW_PRIORITY_MAX_FPS = 30;\n\nconst renderers = new Map();\n\nasync function init(\n key: string,\n animationData: string,\n imgSize: number,\n isLowPriority: boolean,\n onInit: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const json = await extractJson(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 const { reduceFactor, msPerFrame, reducedFramesCount } = calcParams(json, isLowPriority, framesCount);\n\n renderers.set(key, { imgSize, reduceFactor, handle });\n onInit(reduceFactor, msPerFrame, reducedFramesCount);\n}\n\nasync function changeData(\n key: string,\n animationData: string,\n isLowPriority: boolean,\n onInit: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const json = await extractJson(animationData);\n const stringOnWasmHeap = allocate(intArrayFromString(json), 'i8', 0);\n const { handle } = renderers.get(key)!;\n const framesCount = rLottieApi.loadFromData(handle, stringOnWasmHeap);\n\n const { reduceFactor, msPerFrame, reducedFramesCount } = calcParams(json, isLowPriority, framesCount);\n onInit(reduceFactor, msPerFrame, reducedFramesCount);\n}\n\nasync function extractJson(animationData: string) {\n const response = await fetch(animationData);\n const contentType = response.headers.get('Content-Type');\n\n // Support deprecated JSON format cached locally\n if (contentType?.startsWith('text/')) {\n return response.text();\n }\n\n const arrayBuffer = await response.arrayBuffer();\n return inflate(arrayBuffer, { to: 'string' });\n}\n\nfunction calcParams(json: string, isLowPriority: boolean, framesCount: number) {\n const animationData = JSON.parse(json);\n const maxFps = isLowPriority ? LOW_PRIORITY_MAX_FPS : HIGH_PRIORITY_MAX_FPS;\n const sourceFps = animationData.fr || maxFps;\n const reduceFactor = sourceFps % maxFps === 0 ? sourceFps / maxFps : 1;\n\n return {\n reduceFactor,\n msPerFrame: 1000 / (sourceFps / reduceFactor),\n reducedFramesCount: Math.ceil(framesCount / reduceFactor),\n };\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","// 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// 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, [802], () => (__webpack_require__(2993)))\n\t__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n\treturn __webpack_exports__;\n};\n\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 + \".\" + \"acd83f1b28a8893b9dba\" + \".js\";\n};","// This function allow to reference async chunks and sibling chunks for the entrypoint\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","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\t354: 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","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","async","extractJson","animationData","response","fetch","contentType","headers","get","startsWith","text","arrayBuffer","inflate","to","calcParams","json","isLowPriority","framesCount","maxFps","sourceFps","JSON","parse","fr","reduceFactor","msPerFrame","reducedFramesCount","ceil","api","key","imgSize","onInit","stringOnWasmHeap","allocate","intArrayFromString","handle","set","changeData","renderFrames","fromIndex","toIndex","onProgress","i","realIndex","bufferPointer","HEAPU8","subarray","Uint8ClampedArray","renderer","delete","onmessage","messageId","name","args","callback","callbackArgs","lastArg","length","ArrayBuffer","undefined","push","isCanceled","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","exports","module","__webpack_modules__","call","m","x","__webpack_exports__","O","result","chunkIds","fn","priority","notFulfilled","Infinity","fulfilled","j","Object","keys","every","splice","r","f","chunkId","all","reduce","promises","u","miniCssF","g","globalThis","this","Function","o","obj","prop","prototype","hasOwnProperty","scriptUrl","location","document","currentScript","src","scripts","getElementsByTagName","Error","replace","p","installedChunks","chunkLoadingGlobal","parentChunkLoadingFunction","bind","moreModules","runtime","pop","then"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"354.a5e899b2a69f227670ec.js","mappings":"uBAAIA,ECAAC,E,gCC0CkC,oBAAXC,QAA0BA,OAAOC,YAqEzBC,KAAKC,MAAM,KACJ,IAAIC,IAAI,CAChD,aAAc,sBAAuB,iBAAkB,0BAA2B,kBAjH7E,MA8IMC,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,OCrF3JG,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,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EAAEW,SACrC,IAAKF,GAAaE,IACbA,EAASC,gBACZH,EAAYE,EAASC,cAAcC,MAC/BJ,GAAW,CACf,IAAIK,EAAUH,EAASI,qBAAqB,UACzCD,EAAQnD,SAAQ8C,EAAYK,EAAQA,EAAQnD,OAAS,GAAGkD,KAK7D,IAAKJ,EAAW,MAAM,IAAIO,MAAM,yDAChCP,EAAYA,EAAUQ,QAAQ,OAAQ,IAAIA,QAAQ,QAAS,IAAIA,QAAQ,YAAa,KACpFhD,EAAoBiD,EAAIT,G,SCXxB,IAAIU,EAAkB,CACrB,IAAK,GAgBNlD,EAAoBwB,EAAE7C,EAAI,CAAC8C,EAASG,KAE/BsB,EAAgBzB,IAElBpG,cAAc2E,EAAoBiD,EAAIjD,EAAoB6B,EAAEJ,KAK/D,IAAI0B,EAAqB9I,KAA6B,uBAAIA,KAA6B,wBAAK,GACxF+I,EAA6BD,EAAmBtD,KAAKwD,KAAKF,GAC9DA,EAAmBtD,KAvBC5E,IACnB,IAAK2F,EAAU0C,EAAaC,GAAWtI,EACvC,IAAI,IAAIgF,KAAYqD,EAChBtD,EAAoBmC,EAAEmB,EAAarD,KACrCD,EAAoBO,EAAEN,GAAYqD,EAAYrD,IAIhD,IADGsD,GAASA,EAAQvD,GACdY,EAASlB,QACdwD,EAAgBtC,EAAS4C,OAAS,EACnCJ,EAA2BnI,K,GXnBxBpB,EAAOmG,EAAoBQ,EAC/BR,EAAoBQ,EAAI,IAChBR,EAAoBzF,EAAE,KAAKkJ,KAAK5J,GYDdmG,EAAoBQ,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/createWorkerInterface.ts","webpack://telegram-t/./src/lib/rlottie/rlottie.worker.ts","webpack://telegram-t/webpack/bootstrap","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/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(802).then(next);\n};","export const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION!;\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 PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const DEBUG_PAYMENT_SMART_GLOCAL = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 500;\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 200;\nexport const GLOBAL_STATE_CACHE_CHATS_WITH_MESSAGES_LIMIT = 30;\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-v8';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const AUTODOWNLOAD_FILESIZE_MB_LIMITS = [1, 5, 10, 50, 100, 500];\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\nexport const GROUP_CALL_PARTICIPANTS_LIMIT = 100;\nexport const REACTION_LIST_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\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\nexport const CUSTOM_APPENDIX_ATTRIBUTE = 'data-has-custom-appendix';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const 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 = 100;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const STICKER_SIZE_JOIN_REQUESTS = 140;\nexport const STICKER_SIZE_INVITES = 140;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const NO_STICKER_SET_ID = 'NO_STICKER_SET';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\nexport const VIDEO_WEBM_TYPE = 'video/webm';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const 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\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: any) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n 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 { inflate } from 'pako/dist/pako_inflate';\nimport 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 HIGH_PRIORITY_MAX_FPS = 60;\nconst LOW_PRIORITY_MAX_FPS = 30;\n\nconst renderers = new Map();\n\nasync function init(\n key: string,\n animationData: string,\n imgSize: number,\n isLowPriority: boolean,\n onInit: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const json = await extractJson(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 const { reduceFactor, msPerFrame, reducedFramesCount } = calcParams(json, isLowPriority, framesCount);\n\n renderers.set(key, { imgSize, reduceFactor, handle });\n onInit(reduceFactor, msPerFrame, reducedFramesCount);\n}\n\nasync function changeData(\n key: string,\n animationData: string,\n isLowPriority: boolean,\n onInit: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const json = await extractJson(animationData);\n const stringOnWasmHeap = allocate(intArrayFromString(json), 'i8', 0);\n const { handle } = renderers.get(key)!;\n const framesCount = rLottieApi.loadFromData(handle, stringOnWasmHeap);\n\n const { reduceFactor, msPerFrame, reducedFramesCount } = calcParams(json, isLowPriority, framesCount);\n onInit(reduceFactor, msPerFrame, reducedFramesCount);\n}\n\nasync function extractJson(animationData: string) {\n const response = await fetch(animationData);\n const contentType = response.headers.get('Content-Type');\n\n // Support deprecated JSON format cached locally\n if (contentType?.startsWith('text/')) {\n return response.text();\n }\n\n const arrayBuffer = await response.arrayBuffer();\n return inflate(arrayBuffer, { to: 'string' });\n}\n\nfunction calcParams(json: string, isLowPriority: boolean, framesCount: number) {\n const animationData = JSON.parse(json);\n const maxFps = isLowPriority ? LOW_PRIORITY_MAX_FPS : HIGH_PRIORITY_MAX_FPS;\n const sourceFps = animationData.fr || maxFps;\n const reduceFactor = sourceFps % maxFps === 0 ? sourceFps / maxFps : 1;\n\n return {\n reduceFactor,\n msPerFrame: 1000 / (sourceFps / reduceFactor),\n reducedFramesCount: Math.ceil(framesCount / reduceFactor),\n };\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","// 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// 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, [802], () => (__webpack_require__(2993)))\n\t__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n\treturn __webpack_exports__;\n};\n\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 + \".\" + \"acd83f1b28a8893b9dba\" + \".js\";\n};","// This function allow to reference async chunks and sibling chunks for the entrypoint\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","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\t354: 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","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","async","extractJson","animationData","response","fetch","contentType","headers","get","startsWith","text","arrayBuffer","inflate","to","calcParams","json","isLowPriority","framesCount","maxFps","sourceFps","JSON","parse","fr","reduceFactor","msPerFrame","reducedFramesCount","ceil","api","key","imgSize","onInit","stringOnWasmHeap","allocate","intArrayFromString","handle","set","changeData","renderFrames","fromIndex","toIndex","onProgress","i","realIndex","bufferPointer","HEAPU8","subarray","Uint8ClampedArray","renderer","delete","onmessage","messageId","name","args","callback","callbackArgs","lastArg","length","ArrayBuffer","undefined","push","isCanceled","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","exports","module","__webpack_modules__","call","m","x","__webpack_exports__","O","result","chunkIds","fn","priority","notFulfilled","Infinity","fulfilled","j","Object","keys","every","splice","r","f","chunkId","all","reduce","promises","u","miniCssF","g","globalThis","this","Function","o","obj","prop","prototype","hasOwnProperty","scriptUrl","location","document","currentScript","src","scripts","getElementsByTagName","Error","replace","p","installedChunks","chunkLoadingGlobal","parentChunkLoadingFunction","bind","moreModules","runtime","pop","then"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/524.e3a446e0b4e9c7ce5ef9.js b/dist/524.f47aff24c24945077d39.js similarity index 99% rename from dist/524.e3a446e0b4e9c7ce5ef9.js rename to dist/524.f47aff24c24945077d39.js index e1701737..5edfc4ff 100644 --- a/dist/524.e3a446e0b4e9c7ce5ef9.js +++ b/dist/524.f47aff24c24945077d39.js @@ -1,2 +1,2 @@ (()=>{"use strict";const e="tt-media-progressive",t="tt-assets",n=("undefined"!=typeof window&&window.innerHeight,Math.round(425),new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),new Set(["image/png","image/gif","image/jpeg"])),s=new Set(["video/mp4"]);new Set([...n,...s]),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(t){const{url:n}=t.request,s=t.request.headers.get("range"),r=/^bytes=(\d+)-(\d+)?$/g.exec(s||""),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/]+)/),n=e&&Number(e[1]),s=null==e?void 0:e[2];if(n&&s)return new Response(new Uint8Array(2).buffer,{status:206,statusText:"Partial Content",headers:[["Content-Range",`bytes 0-1/${n}`],["Accept-Ranges","bytes"],["Content-Length","2"],["Content-Type",s]]})}const l=`${n}?start=${c}&end=${d}`,[u,f]=await async function(t){const n=await self.caches.open(e);return Promise.all([n.match(`${t}&type=arrayBuffer`).then((e=>e?e.arrayBuffer():void 0)),n.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 n=await self.clients.get(e.clientId);if(!n)return;const s=(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(s,i),r.catch((()=>{})).finally((()=>{o.delete(s)})),n.postMessage({type:"requestPart",messageId:s,params:t}),r}(t,{url:n,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:h}=g,m=Math.min(d-c+1,p.byteLength);d=c+m-1;const y=p.slice(0,m),I=[["Content-Range",`bytes ${c}-${d}/${w}`],["Accept-Ranges","bytes"],["Content-Length",String(m)],["Content-Type",h]];return m<=524288&&d<2097151&&async function(t,n,s){const a=await self.caches.open(e);Promise.all([a.put(new Request(`${t}&type=arrayBuffer`),new Response(n)),a.put(new Request(`${t}&type=headers`),new Response(JSON.stringify(s)))])}(l,y,I),new Response(y,{status:206,statusText:"Partial Content",headers:I})}async function c(e){const n=await async function(n,s){try{return await Promise.race([a(3e3).then((()=>Promise.reject(new Error("TIMEOUT")))),(async()=>{const n=await self.caches.open(t),s=await n.match(e.request);return{cache:n,cached:s}})()])}catch(e){return void console.error(e)}}(),{cache:s,cached:i}=n||{};if(s&&i){if(i.ok)return i;await s.delete(e.request)}const o=await fetch(e.request);return o.ok&&s&&s.put(e.request,o.clone()),o}var d,l;self.addEventListener("message",(e=>{const{type:t,messageId:n,result:s}=e.data;if("partResponse"===t){const e=o.get(n);e&&e.resolve(s)}})),(l=d||(d={})).True="1",l.False="0";let u=(new Date).valueOf();const f=new Set,g={};function p(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 w(e){if(e.custom.msg_id)return parseInt(e.custom.msg_id,10)}async function h(){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 h())[0];t&&t.postMessage({type:"playNotificationSound",payload:{id:e}})}function y(e){let{chatId:t,messageId:n,body:s,title:a,icon:i,reaction:o}=e;const r=(new Date).valueOf()-u<1e3,c={body:s,data:{chatId:t,messageId:n,reaction:o,count:1},icon:i||"icon-192x192.png",badge:"icon-192x192.png",tag:String(r?0:t||0),vibrate:[200,100,200]};return Promise.all([m(String(n)||t||""),self.registration.showNotification(a,c)])}async function I(e,t){if(t.chatId&&(e.postMessage({type:"focusMessage",payload:t}),!e.focused))try{await e.focus()}catch(e){}}self.addEventListener("sync",(()=>{u=Date.now()}));const v=/[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",(e=>{const{url:t}=e.request;return t.includes("/progressive/")?(e.respondWith(r(e)),!0):!(!t.startsWith("http")||!t.match(v)||(e.respondWith(c(e)),0))})),self.addEventListener("push",(function(e){const t=function(e){try{return e.data.json()}catch(e){return}}(e);if(!t||t.mute===d.True)return;const n=function(e){return{chatId:p(e),messageId:w(e),title:e.title||"Telegram WebZ",body:e.description}}(t);f.has(n.messageId)?f.delete(n.messageId):e.waitUntil(y(n))})),self.addEventListener("notificationclick",(function(e){const t=self.registration.scope;e.notification.close();const{data:n}=e.notification;e.waitUntil((async()=>{const e=await h();if(await Promise.all(e.map((e=>(g[e.id]=n,I(e,n))))),self.clients.openWindow&&!(e.length>0)){g[0]=n;try{const e=await self.clients.openWindow(t);e&&(g[e.id]=n)}catch(e){}}})())})),self.addEventListener("message",(function(e){if(!e.data)return;const t=e.source;if("clientReady"===e.data.type){const n=g[t.id]||g[0];n&&(delete g[t.id],delete g[0],e.waitUntil(I(t,n)))}if("showMessageNotification"===e.data.type){const t=e.data.payload;e.waitUntil((async()=>(t.chatId&&(await self.registration.getNotifications({tag:t.chatId})).forEach((e=>e.close())),f.add(t.messageId),y(t)))())}"closeMessageNotifications"===e.data.type&&e.waitUntil(async function(e){let{chatId:t,lastReadInboxMessageId:n}=e;const s=await self.registration.getNotifications(),a=n||Number.MAX_VALUE;s.forEach((e=>{("0"===e.tag||e.data.chatId===t&&e.data.messageId<=a)&&e.close()}))}(e.data.payload))}))})(); -//# sourceMappingURL=524.e3a446e0b4e9c7ce5ef9.js.map \ No newline at end of file +//# sourceMappingURL=524.f47aff24c24945077d39.js.map \ No newline at end of file diff --git a/dist/524.e3a446e0b4e9c7ce5ef9.js.map b/dist/524.f47aff24c24945077d39.js.map similarity index 99% rename from dist/524.e3a446e0b4e9c7ce5ef9.js.map rename to dist/524.f47aff24c24945077d39.js.map index 0fc91fa8..51776dd9 100644 --- a/dist/524.e3a446e0b4e9c7ce5ef9.js.map +++ b/dist/524.f47aff24c24945077d39.js.map @@ -1 +1 @@ -{"version":3,"file":"524.e3a446e0b4e9c7ce5ef9.js","mappings":"mBAAO,MAgCMA,EAA+B,uBAI/BC,EAAmB,YA0GnBC,GApGyB,oBAAXC,QAA0BA,OAAOC,YAqEzBC,KAAKC,MAAM,KACJ,IAAIC,IAAI,CAChD,aAAc,sBAAuB,iBAAkB,0BAA2B,kBA6BvC,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,OCjDtJ,MAAME,EAASC,GAAe,IAAIC,SAAeC,IACtDC,YAAW,IAAMD,KAAWF,MC5FxBI,EAAoB,OAIpBC,EAAgB,IAAIC,IAEnBC,eAAeC,EAAsBC,GAC1C,MAAM,IAAEC,GAAQD,EAAEE,QACZC,EAAQH,EAAEE,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IACE,MAAM0D,QAAkB1H,KAAKc,QAAQ0G,WAAWzC,GAC5C2C,IAEFrD,EAAYqD,EAAUzG,IAAM+C,GAE9B,MAAOT,OAQCoE,OCtKd3H,KAAK8D,iBAAiB,WDyKf,SAA6BrF,GAKlC,IAAKA,EAAEuF,KAAM,OACb,MAAM4D,EAASnJ,EAAEmJ,OACjB,GAAoB,gBAAhBnJ,EAAEuF,KAAK7B,KAAwB,CAEjC,MAAM6B,EAAOK,EAAYuD,EAAO3G,KAAOoD,EAAY,GAC/CL,WACKK,EAAYuD,EAAO3G,WACnBoD,EAAY,GACnB5F,EAAEgI,UAAUL,EAAiBwB,EAAQ5D,KAGzC,GAAoB,4BAAhBvF,EAAEuF,KAAK7B,KAAoC,CAE7C,MAAM+E,EAAiCzI,EAAEuF,KAAKuB,QAC9C9G,EAAEgI,UAAU,WAENS,EAAazB,eACazF,KAAKiF,aAAa4C,iBAAiB,CAAE3B,IAAKgB,EAAazB,UACrEqC,SAASC,GAAMA,EAAET,UAGjClD,EAAmB4D,IAAId,EAAanG,WAC7ByE,EAAiB0B,IARd,IAYM,8BAAhBzI,EAAEuF,KAAK7B,MACT1D,EAAEgI,UA5HNlI,eAAA,GAG0B,IAHQ,OAChCkH,EADgC,uBAEhCwC,GACwB,EACxB,MAAMC,QAAsBlI,KAAKiF,aAAa4C,mBACxCM,EAAgBF,GAA0B/I,OAAOkJ,UACvDF,EAAcJ,SAASZ,KAEE,MAArBA,EAAahB,KACTgB,EAAalD,KAAKyB,SAAWA,GAAUyB,EAAalD,KAAKjD,WAAaoH,IAE1EjB,EAAaI,WAiHHe,CAAmB5J,EAAEuF,KAAKuB,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/util/generateIdFor.ts","webpack://telegram-t/./src/serviceWorker/assetCache.ts","webpack://telegram-t/./src/serviceWorker/pushNotification.ts","webpack://telegram-t/./src/serviceWorker.ts"],"sourcesContent":["export const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION!;\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 PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const DEBUG_PAYMENT_SMART_GLOCAL = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 500;\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 200;\nexport const GLOBAL_STATE_CACHE_CHATS_WITH_MESSAGES_LIMIT = 30;\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-v8';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const AUTODOWNLOAD_FILESIZE_MB_LIMITS = [1, 5, 10, 50, 100, 500];\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\nexport const GROUP_CALL_PARTICIPANTS_LIMIT = 100;\nexport const REACTION_LIST_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\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\nexport const CUSTOM_APPENDIX_ATTRIBUTE = 'data-has-custom-appendix';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const 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 = 100;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const STICKER_SIZE_JOIN_REQUESTS = 140;\nexport const STICKER_SIZE_INVITES = 140;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const NO_STICKER_SET_ID = 'NO_STICKER_SET';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\nexport const VIDEO_WEBM_TYPE = 'video/webm';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const 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\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","const generateIdFor = (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\nexport default generateIdFor;\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 reaction?: string;\n};\n\ntype FocusMessageData = {\n chatId?: string;\n messageId?: number;\n reaction?: 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 reaction,\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 reaction,\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 // Don't 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: FocusMessageData) {\n if (!data.chatId) return;\n client.postMessage({\n type: 'focusMessage',\n payload: data,\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 === 'showMessageNotification') {\n // store messageId for already shown notification\n const notification: NotificationData = e.data.payload;\n e.waitUntil((async () => {\n // Close existing notification if it is already shown\n if (notification.chatId) {\n const notifications = await self.registration.getNotifications({ tag: notification.chatId });\n notifications.forEach((n) => n.close());\n }\n // Mark this notification as shown if it was handled locally\n shownNotifications.add(notification.messageId);\n return showNotification(notification);\n })());\n }\n\n if (e.data.type === 'closeMessageNotifications') {\n e.waitUntil(closeNotifications(e.data.payload));\n }\n}\n\nself.addEventListener('sync', () => {\n lastSyncAt = Date.now();\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"],"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","respondForProgressive","e","url","request","range","headers","get","bytes","exec","start","Number","end","match","fileSize","mimeType","Response","Uint8Array","buffer","status","statusText","cacheKey","cachedArrayBuffer","cachedHeaders","cache","self","caches","open","all","then","r","arrayBuffer","undefined","json","fetchFromCache","partInfo","params","clientId","client","clients","messageId","store","id","String","random","replace","hasOwnProperty","generateIdFor","requestState","promise","race","reject","Error","Object","assign","set","catch","finally","delete","postMessage","type","requestPart","err","fullSize","partSize","min","byteLength","arrayBufferPart","slice","put","Request","JSON","stringify","saveToCache","respondWithCache","cacheResult","cb","timeout","cached","console","error","withTimeout","ok","remote","fetch","clone","Boolean","addEventListener","result","data","lastSyncAt","Date","valueOf","shownNotifications","clickBuffer","getChatId","custom","from_id","chat_id","channel_id","getMessageId","msg_id","parseInt","getClients","appUrl","URL","registration","scope","origin","matchAll","filter","playNotificationSound","payload","showNotification","chatId","body","title","icon","reaction","isFirstBatch","options","count","badge","tag","vibrate","focusChatMessage","focused","focus","now","ASSET_CACHE_PATTERN","waitUntil","skipWaiting","claim","includes","respondWith","startsWith","getPushData","mute","True","notification","description","getNotificationData","has","close","map","openWindow","length","newClient","notifyClients","source","getNotifications","forEach","n","add","lastReadInboxMessageId","notifications","lastMessageId","MAX_VALUE","closeNotifications"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"524.f47aff24c24945077d39.js","mappings":"mBAAO,MAgCMA,EAA+B,uBAI/BC,EAAmB,YA0GnBC,GApGyB,oBAAXC,QAA0BA,OAAOC,YAqEzBC,KAAKC,MAAM,KACJ,IAAIC,IAAI,CAChD,aAAc,sBAAuB,iBAAkB,0BAA2B,kBA6BvC,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,KAA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egram-t/./src/config.ts","webpack://telegram-t/./src/util/schedulers.ts","webpack://telegram-t/./src/serviceWorker/progressive.ts","webpack://telegram-t/./src/util/generateIdFor.ts","webpack://telegram-t/./src/serviceWorker/assetCache.ts","webpack://telegram-t/./src/serviceWorker/pushNotification.ts","webpack://telegram-t/./src/serviceWorker.ts"],"sourcesContent":["export const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION!;\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 PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const DEBUG_PAYMENT_SMART_GLOCAL = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 500;\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 200;\nexport const GLOBAL_STATE_CACHE_CHATS_WITH_MESSAGES_LIMIT = 30;\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-v8';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const AUTODOWNLOAD_FILESIZE_MB_LIMITS = [1, 5, 10, 50, 100, 500];\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\nexport const GROUP_CALL_PARTICIPANTS_LIMIT = 100;\nexport const REACTION_LIST_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\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\nexport const CUSTOM_APPENDIX_ATTRIBUTE = 'data-has-custom-appendix';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const 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 = 100;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const STICKER_SIZE_JOIN_REQUESTS = 140;\nexport const STICKER_SIZE_INVITES = 140;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const NO_STICKER_SET_ID = 'NO_STICKER_SET';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\nexport const VIDEO_WEBM_TYPE = 'video/webm';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const 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\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","const generateIdFor = (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\nexport default generateIdFor;\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 reaction?: string;\n};\n\ntype FocusMessageData = {\n chatId?: string;\n messageId?: number;\n reaction?: 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 reaction,\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 reaction,\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 // Don't 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: FocusMessageData) {\n if (!data.chatId) return;\n client.postMessage({\n type: 'focusMessage',\n payload: data,\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 === 'showMessageNotification') {\n // store messageId for already shown notification\n const notification: NotificationData = e.data.payload;\n e.waitUntil((async () => {\n // Close existing notification if it is already shown\n if (notification.chatId) {\n const notifications = await self.registration.getNotifications({ tag: notification.chatId });\n notifications.forEach((n) => n.close());\n }\n // Mark this notification as shown if it was handled locally\n shownNotifications.add(notification.messageId);\n return showNotification(notification);\n })());\n }\n\n if (e.data.type === 'closeMessageNotifications') {\n e.waitUntil(closeNotifications(e.data.payload));\n }\n}\n\nself.addEventListener('sync', () => {\n lastSyncAt = Date.now();\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"],"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","respondForProgressive","e","url","request","range","headers","get","bytes","exec","start","Number","end","match","fileSize","mimeType","Response","Uint8Array","buffer","status","statusText","cacheKey","cachedArrayBuffer","cachedHeaders","cache","self","caches","open","all","then","r","arrayBuffer","undefined","json","fetchFromCache","partInfo","params","clientId","client","clients","messageId","store","id","String","random","replace","hasOwnProperty","generateIdFor","requestState","promise","race","reject","Error","Object","assign","set","catch","finally","delete","postMessage","type","requestPart","err","fullSize","partSize","min","byteLength","arrayBufferPart","slice","put","Request","JSON","stringify","saveToCache","respondWithCache","cacheResult","cb","timeout","cached","console","error","withTimeout","ok","remote","fetch","clone","Boolean","addEventListener","result","data","lastSyncAt","Date","valueOf","shownNotifications","clickBuffer","getChatId","custom","from_id","chat_id","channel_id","getMessageId","msg_id","parseInt","getClients","appUrl","URL","registration","scope","origin","matchAll","filter","playNotificationSound","payload","showNotification","chatId","body","title","icon","reaction","isFirstBatch","options","count","badge","tag","vibrate","focusChatMessage","focused","focus","now","ASSET_CACHE_PATTERN","waitUntil","skipWaiting","claim","includes","respondWith","startsWith","getPushData","mute","True","notification","description","getNotificationData","has","close","map","openWindow","length","newClient","notifyClients","source","getNotifications","forEach","n","add","lastReadInboxMessageId","notifications","lastMessageId","MAX_VALUE","closeNotifications"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/616.dfb0d60d06da102bbad4.css b/dist/616.421a1d053cdd90ce3d23.css similarity index 93% rename from dist/616.dfb0d60d06da102bbad4.css rename to dist/616.421a1d053cdd90ce3d23.css index 64f763d0..170c95da 100644 --- a/dist/616.dfb0d60d06da102bbad4.css +++ b/dist/616.421a1d053cdd90ce3d23.css @@ -34,11 +34,11 @@ .ComposerEmbeddedMessage{height:2.625rem;transition:height 150ms ease-out,opacity 150ms ease-out}.select-mode-active+.middle-column-footer .ComposerEmbeddedMessage{display:none}.ComposerEmbeddedMessage:not(.open){height:0 !important}body.animation-level-0 .ComposerEmbeddedMessage{transition:none !important}.ComposerEmbeddedMessage>div{display:flex;align-items:center;padding-right:.625rem;padding-top:.1875rem}.ComposerEmbeddedMessage>div>.Button{flex-shrink:0;background:none !important;width:3.5rem;height:2.875rem;margin:0 -0.0625rem 0 0;padding:0;align-self:center}@media(max-width: 600px){.ComposerEmbeddedMessage>div>.Button{width:2.875rem}} .WebPagePreview{height:2.625rem;transition:height 150ms ease-out,opacity 150ms ease-out;--accent-color: var(--color-primary)}body.animation-level-0 .WebPagePreview{transition:none !important}.select-mode-active+.middle-column-footer .WebPagePreview{display:none}.WebPagePreview:not(.open){height:0 !important}.WebPagePreview>div{display:flex;align-items:center;padding-right:.625rem;padding-top:.1875rem}.ComposerEmbeddedMessage+.WebPagePreview{margin-top:.75rem}.WebPagePreview>div>.Button{flex-shrink:0;background:none !important;width:3.5rem;height:2.875rem;margin:0 -0.0625rem 0 0;padding:0;align-self:center}@media(max-width: 600px){.WebPagePreview>div>.Button{width:2.875rem}}.WebPagePreview .WebPage{flex-grow:1;margin:.1875rem 0 .1875rem .125rem;max-width:calc(100% - 3.375rem)}.WebPagePreview .WebPage::before{top:.125rem;bottom:.0625rem}.WebPagePreview .WebPage.with-video .media-inner{display:none}.WebPagePreview .WebPage .site-title,.WebPagePreview .WebPage .site-description{flex:1;max-width:100%;max-height:1rem}.WebPagePreview .WebPage .site-title{margin-top:.125rem;margin-bottom:.1875rem}.WebPagePreview .WebPage .site-description{overflow:hidden;white-space:nowrap;text-overflow:ellipsis} .Composer{align-items:flex-end}.select-mode-active+.middle-column-footer .Composer{position:absolute;padding-right:2rem;bottom:env(safe-area-inset-bottom)}@media(max-width: 600px){.select-mode-active+.middle-column-footer .Composer{padding-right:1rem}}.select-mode-active+.middle-column-footer .Composer::before{right:2.125rem}@media(max-width: 600px){.select-mode-active+.middle-column-footer .Composer::before{right:1rem}}.select-mode-active+.middle-column-footer .Composer .svg-appendix{opacity:0}.Composer .form-control{--border-width: 0}@keyframes show-send-as-button{from{width:1rem;transform:scale(0)}to{width:3.5rem;transform:scale(1)}}.Composer>.Button{flex-shrink:0;margin-left:.5rem}.Composer>.Button:not(.danger){color:var(--color-composer-button)}@media(max-width: 600px){.Composer>.Button{width:2.875rem;height:2.875rem}}.Composer>.Button .icon-send,.Composer>.Button .icon-schedule,.Composer>.Button .icon-microphone-alt,.Composer>.Button .icon-check{position:absolute}.Composer>.Button:not(:active):not(:focus):not(:hover) .icon-send,.Composer>.Button:not(:active):not(:focus):not(:hover) .icon-schedule,.Composer>.Button:not(:active):not(:focus):not(:hover) .icon-check{color:var(--color-primary)}.Composer>.Button.cancel{position:relative;z-index:1}.Composer>.Button.cancel:hover,.Composer>.Button.cancel.active{background:var(--color-chat-hover)}.Composer>.Button.recording{position:relative;z-index:0;transition:box-shadow .1s}.Composer>.Button.send .icon-send{animation:grow-icon .4s ease-out}.Composer>.Button.send .icon-microphone-alt,.Composer>.Button.send .icon-check,.Composer>.Button.send .icon-schedule{animation:hide-icon .4s forwards ease-out}.Composer>.Button.schedule .icon-schedule{animation:grow-icon .4s ease-out}.Composer>.Button.schedule .icon-microphone-alt,.Composer>.Button.schedule .icon-check,.Composer>.Button.schedule .icon-send{animation:hide-icon .4s forwards ease-out}.Composer>.Button.record .icon-microphone-alt{animation:grow-icon .4s ease-out}.Composer>.Button.record .icon-send,.Composer>.Button.record .icon-check,.Composer>.Button.record .icon-schedule{animation:hide-icon .4s forwards ease-out}.Composer>.Button.edit .icon-check{animation:grow-icon .4s ease-out}.Composer>.Button.edit .icon-send,.Composer>.Button.edit .icon-microphone-alt,.Composer>.Button.edit .icon-schedule{animation:hide-icon .4s forwards ease-out}.Composer>.Button.not-ready>i{animation-duration:0ms !important}body.animation-level-0 .Composer>.Button .icon-send,body.animation-level-0 .Composer>.Button .icon-microphone-alt,body.animation-level-0 .Composer>.Button .icon-check,body.animation-level-0 .Composer>.Button .icon-schedule,body.animation-level-1 .Composer>.Button .icon-send,body.animation-level-1 .Composer>.Button .icon-microphone-alt,body.animation-level-1 .Composer>.Button .icon-check,body.animation-level-1 .Composer>.Button .icon-schedule{animation-duration:0ms !important}.Composer .send-as-button{z-index:1}body:not(.animation-level-0) .Composer .send-as-button.appear-animation{animation:.25s ease-in-out forwards show-send-as-button;transform-origin:right}.Composer .mobile-symbol-menu-button{width:2.875rem;height:2.875rem;position:relative}.Composer .mobile-symbol-menu-button .icon-smile,.Composer .mobile-symbol-menu-button .icon-keyboard,.Composer .mobile-symbol-menu-button .Spinner{position:absolute}.Composer .mobile-symbol-menu-button .Spinner{--spinner-size: 1.5rem}.Composer .mobile-symbol-menu-button .icon-smile{animation:grow-icon .4s ease-out}.Composer .mobile-symbol-menu-button .icon-keyboard,.Composer .mobile-symbol-menu-button .Spinner{animation:hide-icon .4s forwards ease-out}.Composer .mobile-symbol-menu-button.not-ready>i{animation-duration:0ms !important}.Composer .mobile-symbol-menu-button.is-loading .Spinner{animation:grow-icon .4s ease-out}.Composer .mobile-symbol-menu-button.is-loading .icon-keyboard,.Composer .mobile-symbol-menu-button.is-loading .icon-smile{animation:hide-icon .4s forwards ease-out}.Composer .mobile-symbol-menu-button.menu-opened .icon-keyboard{animation:grow-icon .4s ease-out}.Composer .mobile-symbol-menu-button.menu-opened .icon-smile,.Composer .mobile-symbol-menu-button.menu-opened .Spinner{animation:hide-icon .4s forwards ease-out}#message-compose{flex-grow:1;max-width:calc(100% - 4rem);background:var(--color-background);border-radius:var(--border-radius-messages);border-bottom-right-radius:0;box-shadow:0 1px 2px var(--color-default-shadow);position:relative;z-index:1}#message-compose .svg-appendix{position:absolute;bottom:-0.1875rem;right:-0.551rem;width:.5625rem;height:1.25rem;transition:opacity 200ms;font-size:1rem !important}#message-compose .svg-appendix .corner{fill:var(--color-background)}@media(max-width: 600px){#message-compose{max-width:calc(100% - 3.375rem)}}.message-input-wrapper{display:flex}.message-input-wrapper>.Spinner{align-self:center;--spinner-size: 1.5rem;margin-right:-0.5rem}.message-input-wrapper>.AttachMenu>.Button,.message-input-wrapper>.Button{flex-shrink:0;background:none !important;width:3.5rem;height:3.5rem;margin:0;padding:0;align-self:flex-end}.message-input-wrapper>.AttachMenu>.Button:not(.faded):not(.activated),.message-input-wrapper>.Button:not(.faded):not(.activated){color:var(--color-composer-button)}.message-input-wrapper>.AttachMenu>.Button+.Button,.message-input-wrapper>.AttachMenu>.Button+.AttachMenu,.message-input-wrapper>.Button+.Button,.message-input-wrapper>.Button+.AttachMenu{margin-left:-1rem}@media(max-width: 600px){.message-input-wrapper>.AttachMenu>.Button,.message-input-wrapper>.Button{width:2.875rem;height:2.875rem}.message-input-wrapper>.AttachMenu>.Button+.Button,.message-input-wrapper>.AttachMenu>.Button+.AttachMenu,.message-input-wrapper>.Button+.Button,.message-input-wrapper>.Button+.AttachMenu{margin-left:-0.6875rem}}.message-input-wrapper>.AttachMenu>.Button.bot-commands,.message-input-wrapper>.Button.bot-commands{color:var(--color-primary) !important}body.is-touch-env .message-input-wrapper>.AttachMenu>.Button.bot-commands.activated+.Button.mobile-symbol-menu-button,body.is-touch-env .message-input-wrapper>.Button.bot-commands.activated+.Button.mobile-symbol-menu-button{z-index:calc(var(--z-menu-backdrop) + 1)}.message-input-wrapper>.AttachMenu>.Button.scheduled-button i::after,.message-input-wrapper>.Button.scheduled-button i::after{content:"";position:absolute;top:.75rem;right:.875rem;border:.1875rem solid var(--color-background);box-sizing:content-box;width:.5rem;height:.5rem;border-radius:50%;background:var(--color-green-darker);box-shadow:-0.375rem -0.25rem 0 -0.1875rem var(--color-background)}@media(max-width: 600px){.message-input-wrapper>.AttachMenu>.Button.scheduled-button i::after,.message-input-wrapper>.Button.scheduled-button i::after{top:.5rem;right:.5rem}}.message-input-wrapper>.input-group{flex-grow:1;margin-bottom:0}.message-input-wrapper .recording-state{display:inline-block;position:relative;line-height:3.5rem;height:3.5rem;padding:0 3.125rem 0 1rem;font-family:"Roboto",-apple-system,BlinkMacSystemFont,"Apple Color Emoji","Helvetica Neue",sans-serif}.message-input-wrapper .recording-state::after{content:"";width:.75rem;height:.75rem;background:var(--color-error);border-radius:.375rem;position:absolute;top:50%;margin-top:-0.375rem;right:1.3125rem;animation:recording-blink-like-macos 1.5s infinite}@media(max-width: 600px){.message-input-wrapper .recording-state{height:2.875rem;line-height:2.875rem}}#message-input-text,#caption-input-text{position:relative}#message-input-text .form-control,#caption-input-text .form-control{padding:calc((3.25rem - var(--composer-text-size, 1rem)*1.375)/2 - var(--border-width, 0)*2) calc(.9rem - var(--border-width));overflow:hidden;line-height:1.375;font-family:Roboto,-apple-system,"Apple Color Emoji","Helvetica Neue",sans-serif;unicode-bidi:plaintext;text-align:initial;font-size:var(--composer-text-size, 1rem)}body.is-ios #message-input-text .form-control,body.is-macos #message-input-text .form-control,body.is-ios #caption-input-text .form-control,body.is-macos #caption-input-text .form-control{font-family:system-ui,-apple-system,BlinkMacSystemFont,"Roboto","Apple Color Emoji","Helvetica Neue",sans-serif}#message-input-text .form-control.overflown,#caption-input-text .form-control.overflown{overflow-y:auto;overflow-x:hidden}#message-input-text .form-control.touched+.placeholder-text,#message-input-text .form-control:focus+.placeholder-text,#caption-input-text .form-control.touched+.placeholder-text,#caption-input-text .form-control:focus+.placeholder-text{display:none}#message-input-text .form-control.focus-disabled,#caption-input-text .form-control.focus-disabled{pointer-events:none}#message-input-text .forced-placeholder,#message-input-text .placeholder-text,#caption-input-text .forced-placeholder,#caption-input-text .placeholder-text{position:absolute;color:var(--color-placeholders);pointer-events:none;unicode-bidi:plaintext;text-align:initial;line-height:1.3125;font-size:var(--composer-text-size, 1rem);top:calc((3.25rem - var(--composer-text-size, 1rem)*1.375)/2);bottom:auto;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%}#message-input-text .forced-placeholder,#caption-input-text .forced-placeholder{z-index:var(--z-below);left:0}#message-input-text[dir=rtl] .placeholder-text,#caption-input-text[dir=rtl] .placeholder-text{right:0}#message-input-text .text-entity-link,#caption-input-text .text-entity-link{color:var(--color-links) !important;cursor:default;text-decoration:none}#message-input-text .text-entity-link:hover,#message-input-text .text-entity-link:active,#message-input-text .text-entity-link:visited,#caption-input-text .text-entity-link:hover,#caption-input-text .text-entity-link:active,#caption-input-text .text-entity-link:visited{text-decoration:underline !important}#message-input-text .spoiler,#caption-input-text .spoiler{background-image:url(spoiler-dots-black.b2dd6e4f4a5a520c4ccd..png);background-size:auto min(100%,1.125rem);border-radius:.5rem;padding:0 .3125rem .125rem .3125rem;text-shadow:-2px -2px 0 var(--color-background),2px -2px 0 var(--color-background),-2px 2px 0 var(--color-background),2px 2px 0 var(--color-background)}html.theme-dark #message-input-text .spoiler,html.theme-dark #caption-input-text .spoiler{background-image:url(spoiler-dots-white.ab45f83c6ba729884808..png)}#message-input-text .clone,#caption-input-text .clone{position:absolute;top:0;left:0;opacity:0;pointer-events:none;z-index:-10;unicode-bidi:plaintext;text-align:initial}#message-input-text{flex-grow:1}#message-input-text .form-control{margin-bottom:0;background:transparent !important;border:none !important;border-radius:0 !important;box-shadow:none !important;caret-color:var(--color-text);min-height:3.5rem;max-height:26rem;line-height:1.3125;padding:calc((3.5rem - var(--composer-text-size, 1rem)*1.3125)/2) 0;white-space:pre-wrap;transition:height 100ms ease}@media(max-width: 600px){#message-input-text .form-control{height:2.875rem;min-height:2.875rem;max-height:16rem;padding:calc((2.875rem - var(--composer-text-size, 1rem)*1.3125)/2) 0;overflow:auto}}body.animation-level-0 #message-input-text .form-control{transition:none !important}#message-input-text .forced-placeholder,#message-input-text .placeholder-text{top:calc((3.5rem - var(--composer-text-size, 1rem)*1.3125)/2)}@media(max-width: 600px){#message-input-text .forced-placeholder,#message-input-text .placeholder-text{top:calc((2.875rem - var(--composer-text-size, 1rem)*1.3125)/2)}}#message-input-text:not(:only-child) .form-control{padding-left:0;padding-right:0}.ComposerEmbeddedMessage+.message-input-wrapper #message-input-text .form-control.overflown,.WebPagePreview+.message-input-wrapper #message-input-text .form-control.overflown{margin-top:.75rem}#message-input-text .emoji{width:1.25rem;height:1.25rem;margin:0 1px -5px;vertical-align:0;pointer-events:none}#caption-input-text .form-control{height:3.25rem;min-height:3.25rem;max-height:15rem}#caption-input-text .placeholder-text{bottom:.8125rem;left:.9375rem}.composer-tooltip{position:absolute;bottom:calc(100% + .5rem);left:0;width:100%;background:var(--color-background);border-radius:var(--border-radius-messages);padding:.5rem 0;max-height:15rem;overflow-x:hidden;overflow-y:auto;box-shadow:0 1px 2px var(--color-default-shadow);opacity:0;transform:translateY(1.5rem);transform-origin:bottom;transition:opacity var(--layer-transition),transform var(--layer-transition)}@supports(overflow-y: overlay){.composer-tooltip{overflow-y:overlay;overflow-x:hidden}}.composer-tooltip:not(.shown){display:none}.composer-tooltip.open{opacity:1;transform:translateY(0)}.composer-tooltip .Loading{margin:1rem 0}@keyframes recording-blink-like-macos{from{opacity:1}to{opacity:.3}} -#middle-column-bg{position:absolute;top:0;left:0;bottom:0;right:0;overflow:hidden;z-index:-1;background-color:var(--theme-background-color)}body:not(.animation-level-0) #root #middle-column-bg{transition:background-color .2s}#middle-column-bg::after{content:"";position:absolute;top:0;left:0;bottom:0;right:0;background-color:var(--theme-background-color);background-position:center;background-repeat:no-repeat;background-size:cover}body:not(.animation-level-0) #root #middle-column-bg::after{transition:transform var(--layer-transition),background-image .2s}body.animation-level-0 #middle-column-bg::after{transition:none}.theme-light #middle-column-bg::after{background-image:url(chat-bg.f607e788298d8a7de37a..jpg)}@media(max-width: 600px){.theme-light #middle-column-bg::after{background-image:url(chat-bg-mobile.3ebe59c803c10092f223..jpg)}}.theme-dark #middle-column-bg::after{background-image:url(chat-bg-dark.4d8c9dce3544b239b64b..png);background-position:top left;background-size:650px;background-repeat:repeat}.custom-bg-color:not(.custom-bg-image) #middle-column-bg::after{opacity:0}.custom-bg-image #middle-column-bg::after{background-image:var(--custom-background) !important;filter:none;transform:scale(1.1)}.custom-bg-image.blurred #middle-column-bg::after{filter:blur(12px)}@media screen and (min-width: 1276px){body.animation-level-2 #middle-column-bg::after{margin:-16rem -5rem -20rem 0;overflow:hidden;transform:scale(1);transform-origin:left center;transition:transform var(--layer-transition)}html.theme-light body.animation-level-2 #Main.right-column-open #MiddleColumn:not(.custom-bg-image) #middle-column-bg::after{transform:scale(0.67) !important}}@media screen and (min-width: 1921px){html.theme-light body.animation-level-2 #Main.right-column-open #MiddleColumn:not(.custom-bg-image) #middle-column-bg::after{transform:scale(0.8) !important}}@media screen and (min-width: 2600px){html.theme-light body.animation-level-2 #Main.right-column-open #MiddleColumn:not(.custom-bg-image) #middle-column-bg::after{transform:scale(0.95) !important}}#MiddleColumn{display:flex;justify-content:center;height:100%;position:relative;z-index:1;min-width:0}@media(max-width: 600px){#MiddleColumn{overflow:hidden}}#MiddleColumn .messages-layout{--slide-transition: 450ms cubic-bezier(0.25, 1, 0.5, 1);display:flex;flex-direction:column;align-items:center;width:100%;height:100%;position:relative;overflow:hidden}#MiddleColumn .messages-layout>.Transition{width:100%;height:100%;overflow:hidden}#MiddleColumn .messages-layout>.Transition>div{display:flex;flex-direction:column;align-items:center}#MiddleColumn .Composer #message-compose{transform:scaleX(1) translateX(0);transition:transform var(--select-transition),border-bottom-right-radius var(--select-transition)}#MiddleColumn .Composer #message-compose::before{transform:scaleX(-1) translateX(0);transition:transform var(--select-transition)}body.animation-level-0 #MiddleColumn .Composer #message-compose,body.animation-level-0 #MiddleColumn .Composer #message-compose::before{transition:none !important}#MiddleColumn .Composer .message-input-wrapper,#MiddleColumn .Composer::before{opacity:1;transition:opacity var(--select-transition)}body.animation-level-0 #MiddleColumn .Composer .message-input-wrapper,body.animation-level-0 #MiddleColumn .Composer::before{transition:none !important}#MiddleColumn .Composer>.Button{opacity:1;transform:scale(1);transition:opacity var(--select-transition),transform var(--select-transition),background-color .15s,color .15s}body.animation-level-0 #MiddleColumn .Composer>.Button{transition:none !important}#MiddleColumn .Composer.hover-disabled,#MiddleColumn .Composer:not(.shown){pointer-events:none}#MiddleColumn .Composer:not(.shown) .ComposerEmbeddedMessage{height:0}#MiddleColumn .Composer:not(.shown) #message-compose{transform:scaleX(var(--composer-hidden-scale, 1)) translateX(var(--composer-translate-x, 0));border-bottom-right-radius:var(--border-radius-messages)}#MiddleColumn .Composer:not(.shown) #message-compose::before{transform:scaleX(-1) translateX(200%)}#MiddleColumn .Composer:not(.shown) #editable-message-text{height:3.5rem !important}@media(max-width: 600px){#MiddleColumn .Composer:not(.shown) #editable-message-text{height:2.5rem !important}}#MiddleColumn .Composer:not(.shown) .message-input-wrapper,#MiddleColumn .Composer:not(.shown)::before{opacity:0}#MiddleColumn .Composer:not(.shown)>.Button{opacity:0 !important;transform:scale(0.5)}#MiddleColumn .messaging-disabled{transform:scaleX(1);transition:transform var(--select-transition)}#MiddleColumn .messaging-disabled .messaging-disabled-inner span{opacity:1;transition:opacity var(--select-transition)}body.animation-level-0 #MiddleColumn .messaging-disabled .messaging-disabled-inner span{transition:none !important}body.animation-level-0 #MiddleColumn .messaging-disabled{transition:none !important}#MiddleColumn .messaging-disabled:not(.shown){transform:scaleX(var(--composer-hidden-scale, 1));pointer-events:none}#MiddleColumn .messaging-disabled:not(.shown) .messaging-disabled-inner span{opacity:0}#MiddleColumn .messaging-disabled-inner{width:100%;padding:1rem;border-radius:var(--border-radius-messages);background:var(--color-background);color:var(--color-text-secondary);text-align:center;box-shadow:0 1px 2px var(--color-default-shadow)}#MiddleColumn .middle-column-footer{width:100%;max-width:var(--messages-container-width);padding:0 1rem;position:relative;display:flex;align-items:flex-end;z-index:var(--z-middle-footer);transform:translate3d(0, 0, 0);transition:top 200ms,transform var(--layer-transition)}body.animation-level-0 #MiddleColumn .middle-column-footer{transition:none !important}@media(min-width: 1276px){#MiddleColumn .middle-column-footer{width:calc(100% - var(--right-column-width))}#Main.right-column-open #MiddleColumn .middle-column-footer{transform:translate3d(calc(var(--right-column-width) / -2), 0, 0)}}@media(max-width: 600px){#MiddleColumn .middle-column-footer{padding:0 .5rem}body.is-symbol-menu-open #MiddleColumn .middle-column-footer{transform:translate3d(0, calc(-1 * (var(--symbol-menu-height) + var(--symbol-menu-footer-height))), 0)}}#MiddleColumn .middle-column-footer:not(.no-composer){padding-bottom:env(safe-area-inset-bottom);top:0}body.keyboard-visible #MiddleColumn .middle-column-footer:not(.no-composer){top:env(safe-area-inset-bottom)}#MiddleColumn .middle-column-footer::before{content:"";position:absolute;top:-0.5625rem;left:0;right:0;height:1px;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%);opacity:0;transition:opacity 350ms ease}@media(max-width: 600px){#MiddleColumn .middle-column-footer::before{left:-2%;right:-2%}}#MiddleColumn .middle-column-footer.with-notch::before{opacity:1}html.theme-dark #MiddleColumn .middle-column-footer::before{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%)}.Composer,.MessageSelectToolbar,.messaging-disabled{margin-bottom:1.25rem}@media(max-width: 600px){.Composer,.MessageSelectToolbar,.messaging-disabled{margin-bottom:.5rem}}.Composer,.MessageSelectToolbar,.unpin-all-button,.join-subscribe-button,.messaging-disabled{width:100%;display:flex;justify-content:center;position:relative}.mask-image-disabled .MessageSelectToolbar-inner,.mask-image-disabled .unpin-all-button,.mask-image-disabled .join-subscribe-button,.mask-image-disabled .messaging-disabled{box-shadow:0 .25rem .5rem .125rem var(--color-default-shadow);border-radius:var(--border-radius-messages)}.middle-column-footer-button-container{width:100%;display:flex;justify-content:center;position:absolute;padding-bottom:1.25rem}.middle-column-footer-button-container .unpin-all-button{text-transform:capitalize;color:var(--color-black)}@media(hover: hover){.middle-column-footer-button-container .unpin-all-button:hover .icon-unpin{color:var(--color-white)}}@media(max-width: 600px){.middle-column-footer-button-container .unpin-all-button:active .icon-unpin,.middle-column-footer-button-container .unpin-all-button:focus .icon-unpin{color:var(--color-white)}}.middle-column-footer-button-container .unpin-all-button .icon-unpin{margin-inline-start:-0.4375rem;margin-inline-end:.75rem;color:var(--color-text-secondary);font-size:1.5rem;transition:color .15s}.middle-column-footer-button-container .join-subscribe-button,.middle-column-footer-button-container .unpin-all-button{height:3.5rem;transform:scaleX(1);transition:transform var(--select-transition),background-color .15s,color .15s}.select-mode-active+.middle-column-footer .middle-column-footer-button-container .join-subscribe-button,.select-mode-active+.middle-column-footer .middle-column-footer-button-container .unpin-all-button{box-shadow:none;transform:scaleX(var(--unpin-hidden-scale))}@media(max-width: 600px){.middle-column-footer-button-container .join-subscribe-button,.middle-column-footer-button-container .unpin-all-button{height:2.5rem}}@media(max-width: 600px){.middle-column-footer-button-container{padding-bottom:calc(.75rem + env(safe-area-inset-bottom))}}.mask-image-disabled .middle-column-footer-button-container::before{background:unset} +#middle-column-bg{position:absolute;top:0;left:0;bottom:0;right:0;overflow:hidden;z-index:-1;background-color:var(--theme-background-color)}body:not(.animation-level-0) #root #middle-column-bg{transition:background-color .2s}#middle-column-bg::after{content:"";position:absolute;top:0;left:0;bottom:0;right:0;background-color:var(--theme-background-color);background-position:center;background-repeat:no-repeat;background-size:cover}body:not(.animation-level-0) #root #middle-column-bg::after{transition:transform var(--layer-transition),background-image .2s}body.animation-level-0 #middle-column-bg::after{transition:none}.theme-light #middle-column-bg::after{background-image:url(chat-bg.f607e788298d8a7de37a..jpg)}@media(max-width: 600px){.theme-light #middle-column-bg::after{background-image:url(chat-bg-mobile.3ebe59c803c10092f223..jpg)}}.theme-dark #MiddleColumn:not(.custom-bg-image) #middle-column-bg::after{background-image:url(chat-bg-dark.4d8c9dce3544b239b64b..png);background-position:top left;background-size:650px;background-repeat:repeat}.custom-bg-color:not(.custom-bg-image) #middle-column-bg::after{opacity:0}.custom-bg-image #middle-column-bg::after{background-image:var(--custom-background) !important;filter:none;transform:scale(1.1)}.custom-bg-image.blurred #middle-column-bg::after{filter:blur(12px)}@media screen and (min-width: 1276px){body.animation-level-2 #middle-column-bg::after{margin:-16rem -5rem -20rem 0;overflow:hidden;transform:scale(1);transform-origin:left center;transition:transform var(--layer-transition)}html.theme-light body.animation-level-2 #Main.right-column-open #MiddleColumn:not(.custom-bg-image) #middle-column-bg::after{transform:scale(0.67) !important}}@media screen and (min-width: 1921px){html.theme-light body.animation-level-2 #Main.right-column-open #MiddleColumn:not(.custom-bg-image) #middle-column-bg::after{transform:scale(0.8) !important}}@media screen and (min-width: 2600px){html.theme-light body.animation-level-2 #Main.right-column-open #MiddleColumn:not(.custom-bg-image) #middle-column-bg::after{transform:scale(0.95) !important}}#MiddleColumn{display:flex;justify-content:center;height:100%;position:relative;z-index:1;min-width:0}@media(max-width: 600px){#MiddleColumn{overflow:hidden}}#MiddleColumn .messages-layout{--slide-transition: 450ms cubic-bezier(0.25, 1, 0.5, 1);display:flex;flex-direction:column;align-items:center;width:100%;height:100%;position:relative;overflow:hidden}#MiddleColumn .messages-layout>.Transition{width:100%;height:100%;overflow:hidden}#MiddleColumn .messages-layout>.Transition>div{display:flex;flex-direction:column;align-items:center}#MiddleColumn .Composer #message-compose{transform:scaleX(1) translateX(0);transition:transform var(--select-transition),border-bottom-right-radius var(--select-transition)}#MiddleColumn .Composer #message-compose::before{transform:scaleX(-1) translateX(0);transition:transform var(--select-transition)}body.animation-level-0 #MiddleColumn .Composer #message-compose,body.animation-level-0 #MiddleColumn .Composer #message-compose::before{transition:none !important}#MiddleColumn .Composer .message-input-wrapper,#MiddleColumn .Composer::before{opacity:1;transition:opacity var(--select-transition)}body.animation-level-0 #MiddleColumn .Composer .message-input-wrapper,body.animation-level-0 #MiddleColumn .Composer::before{transition:none !important}#MiddleColumn .Composer>.Button{opacity:1;transform:scale(1);transition:opacity var(--select-transition),transform var(--select-transition),background-color .15s,color .15s}body.animation-level-0 #MiddleColumn .Composer>.Button{transition:none !important}#MiddleColumn .Composer.hover-disabled,#MiddleColumn .Composer:not(.shown){pointer-events:none}#MiddleColumn .Composer:not(.shown) .ComposerEmbeddedMessage{height:0}#MiddleColumn .Composer:not(.shown) #message-compose{transform:scaleX(var(--composer-hidden-scale, 1)) translateX(var(--composer-translate-x, 0));border-bottom-right-radius:var(--border-radius-messages)}#MiddleColumn .Composer:not(.shown) #message-compose::before{transform:scaleX(-1) translateX(200%)}#MiddleColumn .Composer:not(.shown) #editable-message-text{height:3.5rem !important}@media(max-width: 600px){#MiddleColumn .Composer:not(.shown) #editable-message-text{height:2.5rem !important}}#MiddleColumn .Composer:not(.shown) .message-input-wrapper,#MiddleColumn .Composer:not(.shown)::before{opacity:0}#MiddleColumn .Composer:not(.shown)>.Button{opacity:0 !important;transform:scale(0.5)}#MiddleColumn .messaging-disabled{transform:scaleX(1);transition:transform var(--select-transition)}#MiddleColumn .messaging-disabled .messaging-disabled-inner span{opacity:1;transition:opacity var(--select-transition)}body.animation-level-0 #MiddleColumn .messaging-disabled .messaging-disabled-inner span{transition:none !important}body.animation-level-0 #MiddleColumn .messaging-disabled{transition:none !important}#MiddleColumn .messaging-disabled:not(.shown){transform:scaleX(var(--composer-hidden-scale, 1));pointer-events:none}#MiddleColumn .messaging-disabled:not(.shown) .messaging-disabled-inner span{opacity:0}#MiddleColumn .messaging-disabled-inner{width:100%;padding:1rem;border-radius:var(--border-radius-messages);background:var(--color-background);color:var(--color-text-secondary);text-align:center;box-shadow:0 1px 2px var(--color-default-shadow)}#MiddleColumn .middle-column-footer{width:100%;max-width:var(--messages-container-width);padding:0 1rem;position:relative;display:flex;align-items:flex-end;z-index:var(--z-middle-footer);transform:translate3d(0, 0, 0);transition:top 200ms,transform var(--layer-transition)}body.animation-level-0 #MiddleColumn .middle-column-footer{transition:none !important}@media(min-width: 1276px){#MiddleColumn .middle-column-footer{width:calc(100% - var(--right-column-width))}#Main.right-column-open #MiddleColumn .middle-column-footer{transform:translate3d(calc(var(--right-column-width) / -2), 0, 0)}}@media(max-width: 600px){#MiddleColumn .middle-column-footer{padding:0 .5rem}body.is-symbol-menu-open #MiddleColumn .middle-column-footer{transform:translate3d(0, calc(-1 * (var(--symbol-menu-height) + var(--symbol-menu-footer-height))), 0)}}#MiddleColumn .middle-column-footer:not(.no-composer){padding-bottom:env(safe-area-inset-bottom);top:0}body.keyboard-visible #MiddleColumn .middle-column-footer:not(.no-composer){top:env(safe-area-inset-bottom)}#MiddleColumn .middle-column-footer::before{content:"";position:absolute;top:-0.5625rem;left:0;right:0;height:1px;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%);opacity:0;transition:opacity 350ms ease}@media(max-width: 600px){#MiddleColumn .middle-column-footer::before{left:-2%;right:-2%}}#MiddleColumn .middle-column-footer.with-notch::before{opacity:1}html.theme-dark #MiddleColumn .middle-column-footer::before{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%)}.Composer,.MessageSelectToolbar,.messaging-disabled{margin-bottom:1.25rem}@media(max-width: 600px){.Composer,.MessageSelectToolbar,.messaging-disabled{margin-bottom:.5rem}}.Composer,.MessageSelectToolbar,.unpin-all-button,.join-subscribe-button,.messaging-disabled{width:100%;display:flex;justify-content:center;position:relative}.mask-image-disabled .MessageSelectToolbar-inner,.mask-image-disabled .unpin-all-button,.mask-image-disabled .join-subscribe-button,.mask-image-disabled .messaging-disabled{box-shadow:0 .25rem .5rem .125rem var(--color-default-shadow);border-radius:var(--border-radius-messages)}.middle-column-footer-button-container{width:100%;display:flex;justify-content:center;position:absolute;padding-bottom:1.25rem}.middle-column-footer-button-container .unpin-all-button{text-transform:capitalize;color:var(--color-black)}@media(hover: hover){.middle-column-footer-button-container .unpin-all-button:hover .icon-unpin{color:var(--color-white)}}@media(max-width: 600px){.middle-column-footer-button-container .unpin-all-button:active .icon-unpin,.middle-column-footer-button-container .unpin-all-button:focus .icon-unpin{color:var(--color-white)}}.middle-column-footer-button-container .unpin-all-button .icon-unpin{margin-inline-start:-0.4375rem;margin-inline-end:.75rem;color:var(--color-text-secondary);font-size:1.5rem;transition:color .15s}.middle-column-footer-button-container .join-subscribe-button,.middle-column-footer-button-container .unpin-all-button{height:3.5rem;transform:scaleX(1);transition:transform var(--select-transition),background-color .15s,color .15s}.select-mode-active+.middle-column-footer .middle-column-footer-button-container .join-subscribe-button,.select-mode-active+.middle-column-footer .middle-column-footer-button-container .unpin-all-button{box-shadow:none;transform:scaleX(var(--unpin-hidden-scale))}@media(max-width: 600px){.middle-column-footer-button-container .join-subscribe-button,.middle-column-footer-button-container .unpin-all-button{height:2.5rem}}@media(max-width: 600px){.middle-column-footer-button-container{padding-bottom:calc(.75rem + env(safe-area-inset-bottom))}}.mask-image-disabled .middle-column-footer-button-container::before{background:unset} .RightHeader{display:flex;align-items:center;height:var(--header-height);padding:.5rem .8125rem;pointer-events:auto}@media(max-width: 600px){.RightHeader{padding:.5rem}}.RightHeader .close-button{flex-shrink:0}.RightHeader>.Transition{flex:1;height:100%}.RightHeader>.Transition>div{display:flex;align-items:center}.RightHeader h3{margin-bottom:0;font-size:1.25rem;font-weight:500;margin-left:1.375rem}.RightHeader .tools{display:flex;margin-left:auto}.RightHeader .SearchInput{margin-left:1rem}@media(min-width: 600px){.RightHeader .SearchInput{margin-right:1rem}}.RightHeader .DropdownMenu{margin-left:auto} .Profile{height:100%;display:flex;flex-direction:column;overflow-x:hidden;overflow-y:scroll}@supports(overflow-y: overlay){.Profile{overflow-y:overlay;overflow-x:hidden}}.Profile>.profile-info>.ChatInfo{grid-area:chat_info}.Profile>.profile-info>.ChatInfo .status.online{color:var(--color-primary)}.Profile>.profile-info>.ChatExtra{padding:.875rem .5rem .5rem;box-shadow:inset 0 -0.0625rem 0 0 var(--color-background-secondary-accent);border-bottom:.625rem solid var(--color-background-secondary)}.Profile>.profile-info>.ChatExtra .narrow{margin-bottom:0}.Profile>.profile-info>.ChatExtra .inactive.no-selection{user-select:auto;-webkit-user-select:auto !important}.Profile>.profile-info>.ChatExtra .Switcher{margin-left:auto}.Profile>.profile-info>.ChatExtra [dir=rtl] .Switcher{margin-left:0;margin-right:auto}.Profile .FloatingActionButton{z-index:1}.shared-media{display:flex;flex-direction:column-reverse}.shared-media .TabList{background:var(--color-background);top:-1px;z-index:1}.shared-media .TabList .Tab{padding:1rem .75rem}.shared-media .TabList .Tab span{white-space:nowrap}.shared-media .TabList .Tab i{bottom:-1rem}.shared-media .Transition{flex:1}.shared-media .content.empty-list{height:100%;padding-top:5rem;display:flex;align-items:flex-start;justify-content:center}.shared-media .content.empty-list .Spinner{--spinner-size: 2.75rem}.shared-media .content.media-list{display:grid;grid-template-columns:repeat(3, 1fr);grid-auto-rows:1fr;grid-gap:.0625rem}.shared-media .content.documents-list{padding:1.25rem}.shared-media .content.documents-list .File+.File{margin-top:1.25rem}.shared-media .content.links-list{padding:1.25rem}.shared-media .content.links-list .ProgressSpinner,.shared-media .content.links-list .message-transfer-progress{display:none}.shared-media .content.audio-list,.shared-media .content.voice-list{padding:1.25rem}.shared-media .content.audio-list .Audio .media-loading,.shared-media .content.voice-list .Audio .media-loading{top:0;left:0;display:flex;align-items:center;justify-content:center}.shared-media .content.audio-list .Audio+.Audio,.shared-media .content.voice-list .Audio+.Audio{margin-top:1.6875rem}.shared-media .content.commonChats-list,.shared-media .content.members-list{padding:.5rem 1rem}@media(max-width: 600px){.shared-media .content.commonChats-list,.shared-media .content.members-list{padding:.5rem 0}.shared-media .content.commonChats-list .ListItem.chat-item-clickable,.shared-media .content.members-list .ListItem.chat-item-clickable{margin:0}} .AddChatMembers{height:100%;overflow:hidden;position:relative}.AddChatMembers-inner{height:100%;overflow:hidden} #RightColumn{position:absolute;top:0;right:0;width:var(--right-column-width);height:100%;padding-right:env(safe-area-inset-right);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}@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)}}#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;transform:translate3d(-20vw, 0, 0);left:env(safe-area-inset-left) !important;width:calc(100vw - env(safe-area-inset-left)) !important}}@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=616.dfb0d60d06da102bbad4.css.map*/ \ No newline at end of file +/*# sourceMappingURL=616.421a1d053cdd90ce3d23.css.map*/ \ No newline at end of file diff --git a/dist/616.dfb0d60d06da102bbad4.css.map b/dist/616.421a1d053cdd90ce3d23.css.map similarity index 88% rename from dist/616.dfb0d60d06da102bbad4.css.map rename to dist/616.421a1d053cdd90ce3d23.css.map index e2bab10b..248291de 100644 --- a/dist/616.dfb0d60d06da102bbad4.css.map +++ b/dist/616.421a1d053cdd90ce3d23.css.map @@ -1 +1 @@ -{"version":3,"file":"616.dfb0d60d06da102bbad4.css","mappings":"AAAA,0BACE,kBACA,MACA,OACA,WAEA,mDACA,UAEA,qCACE,4BACA,UAGF,sCACE,aAIJ,yBACE,iBACA,cACA,aACA,mBACA,qBACA,iBACA,+BACA,2CAEA,qCACE,eAGF,kCACE,wBAGF,qCACE,OACA,gCACA,mBACA,gBACA,wBACA,6BACA,mBAGF,yBACE,qCACE,6BAIJ,qCACE,WAGA,YAEA,yCACE,aACA,mBACA,W;AC5DN,gBACE,kBAEA,oCACE,kBAEA,2HAGE,eACA,eACA,sBACA,6CACA,0BACA,oBAGF,uFAEE,kBACA,OACA,WAGF,4CACE,eAGF,2CACE,aAGF,+CACE,yBAEA,uDACE,qEAGF,sDACE,qEAIJ,iDACE,gBAEA,iHAEE,gBAKN,gCACE,iBACA,cACA,iBACA,6BACA,qBACA,mBACA,WACA,kBACA,mBACA,gBACA,kBACA,cAGF,kDACE,gBACA,UACA,kCAGF,4CACE,sBAGF,0CACE,cACA,kBAGF,8BACE,gBACA,yCAEA,gBClFF,+BD8EA,8BC7EE,mBAGA,mBDoFA,wIACE,2B;AEjGN,eACE,kBACA,WACA,YACA,2BAEA,4DAEA,sCACE,0BACA,UAEA,wBAEA,+CACE,UAIJ,wBACE,wBAEA,yBAHF,wBAKI,sCACA,6BAKF,gFAEE,kBAIA,0DACE,iCAGF,gDACE,0CAKF,0CACE,iCAGF,oDACE,0C;ACnDR,iBACE,YACA,kBACA,aACA,sBACA,gBACA,UAEA,6BACE,OACA,gBAGF,8BACE,YACA,aACA,sBACA,gBAEA,gDACE,gBAEA,6BAEA,2DACE,SAIJ,uCACE,2BACA,sBACA,mBACA,gBACA,UAGF,mCACE,cACA,qBACA,sBAEA,wCACE,mBACA,oBAIJ,0CACE,OACA,gBAIJ,+FAGE,YACA,gBAGF,6BACE,kBACA,YACA,UACA,WACA,c;AClEJ,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,sBAIJ,8BACE,kBACA,oBACA,sBAEA,wCACE,oBAIJ,+EAEE,UACA,mBACA,uEAGF,yLAIE,UACA,qBAIJ,4BACE,kBACA,iBAEA,kDACE,kBACA,2BACA,SACA,YACA,WACA,eACA,kBAGF,gHAEE,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,uBACA,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,8BACA,kCACA,qBACA,mBACA,gBACA,uBACA,mBAEA,2CACE,8BACA,qB;AC1KR,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,WAIJ,0BACE,wDACE,8C;ACrFJ,iBACE,kBACA,OACA,QACA,SAEA,aACA,mBACA,iBACA,mCACA,qCACA,yGACA,+BACA,+DAGE,0DACE,aAIJ,0BArBF,iBAsBI,+BACA,+DAEA,yCACE,sDAIJ,0CACE,mBACA,aACA,mB;AC2CJ,cACE,aACA,mBACA,WACA,+CACA,mCACA,kBACA,+BACA,kBACA,qBACA,mDACA,uDAEA,yBAbF,cAcI,kBAEA,kDACA,qDAGF,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,mEPpLN,oIO0LI,oBAIJ,iDACE,8GAEE,UAEA,8JACE,WAnMN,4HAEE,kBACA,SACA,OACA,QACA,gBACA,uDAEA,aACA,2BACA,oBACA,uBACA,mDACA,oDACA,mCAEA,4IACE,WACA,cACA,kBACA,eACA,OACA,QACA,eACA,uDAGF,sKACE,gBACA,sBAIJ,sDACE,mBACA,aACA,qBAEA,8DACE,gBACA,YAGF,8DACE,sBAGF,oEACE,iBAIJ,8DACE,YACA,cACA,iBAEA,sEACE,YACA,eAGF,4EACE,eAIJ,iFACE,aAsIA,0BACE,iEACE,uDAKN,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,oBAIJ,uEAEE,eACA,uBAEA,0BACE,uHACE,kDAKN,qCACE,uBACA,gBACA,uBAEA,0BACE,6DACE,kDAMR,sBACE,qBAEA,wBACA,yBACA,oBAGF,mDAEE,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,mEAIJ,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,8EACE,qDAMR,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,UAIJ,2CACE,kBACA,iBAGF,oCACE,kBACA,eACA,YACA,gCACA,oBACA,WACA,iBACA,iBACA,gBACA,kBACA,cACA,QACA,MAMF,wFACE,mBAEA,kGACE,qBAKN,yBAtjBA,sEAEE,kBACA,SACA,OACA,QACA,gBACA,uDAEA,aACA,2BACA,oBACA,uBACA,mDACA,oDACA,mCAEA,sFACE,WACA,cACA,kBACA,eACA,OACA,QACA,eACA,uDAGF,gHACE,gBACA,sBAIJ,2BACE,mBACA,aACA,qBAEA,mCACE,gBACA,YAGF,mCACE,sBAGF,yCACE,iBAIJ,mCACE,YACA,cACA,iBAEA,2CACE,YACA,eAGF,iDACE,eAIJ,sDACE,cAsfJ,mBACE,KACE,UAEF,GACE,W;ACnkBJ,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,4DACA,6DACA,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,uBACE,kBACA,aACA,mBACA,uBAEA,oCAEE,wBAEA,eAGF,wCACE,eACA,cACA,eACA,oBAEA,+CACE,YACA,aAGF,mDACE,qBAGF,gDACE,qBAKF,gDACE,eACA,gBAEA,uDACE,eACA,gBAIF,uDACE,kB;AC7CR,aACE,kBACA,eACA,SACA,QACA,aACA,mBACA,gCACA,sBACA,iBACA,WACA,eACA,eACA,0CAEA,oCACE,WACA,YACA,oBAGF,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,gBACA,eAGF,yBACE,QAGF,gDACE,oCAGF,oCACE,uBACA,oBACA,sBAEA,iDACE,8BAIJ,6DACE,gBAGF,kEACE,iBAIA,qCACE,SAEF,yCACE,QAMJ,6DACE,WACA,cACA,cAGF,6DACE,YAGF,6DACE,YAGF,6DACE,Y;ACnJF,wBACE,eAGF,kBACE,oB;ACNJ,SACE,aACA,mBACA,eAEA,qBACE,eAGF,iBACE,sBAGF,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,sBAGF,uBACE,WACA,YACA,kBACA,WACA,YACA,sDACA,oBACA,wBAGF,4BACE,iBACA,qBACA,2BACA,UAIA,qCACE,8BAGF,mCACE,0BAKN,iCACE,GACE,UAEF,KACE,W;ACpHJ,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,sFAGE,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;ACzHJ,gBACE,0BACA,gBAGF,sBACE,kBAGE,+CACE,eACA,aAEA,yBAJF,+CAKI,cAIJ,kDACE,kBACA,MACA,qBACA,cACA,oCACA,kDACA,wBACA,gBAEA,uDACE,kB;AC9BV,UACE,kBACA,kDACA,gBACE,kBAGF,uBACE,mBAGF,wBACE,WACA,cACA,WACA,YACA,kDACA,qDAEA,0BACE,GACE,UAEF,IACE,WAEF,KACE,WAKN,uBACE,WACA,cACA,WACA,YACA,6GACA,iEAEA,yBACE,GACE,4BAEF,IACE,2BAEF,KACE,4B;AChDR,UACE,aACA,sBACA,uBACA,2BAEA,6BACE,kBACA,QACA,SACA,gCACA,kBAaA,sDAXA,yBACE,GACE,yCACA,sCAEF,KACE,yCACA,8BAON,mBACE,KACE,UAEF,GACE,WAIJ,uBACE,gBACA,kBAGF,eACE,+BAGF,eACE,kBACA,QACA,SACA,iCACA,+BAEA,kCAIA,2BACE,WACA,kBACA,SACA,SACA,+BAEA,WACA,YAEA,gCACA,sBACA,kBACA,UAGF,8BACE,aAIJ,qBACE,kBACA,QACA,SACA,kCACA,8DACA,wBACA,aACA,YACA,0FACA,iFACA,kBACA,UAGF,2BACE,kBACA,gBACA,eACA,wBAEA,UAGF,sBACE,kBACA,eACA,SACA,gCACA,WACA,YAEA,UAGF,eACE,cAGF,oCAEE,wDAGF,mBACE,mBAEA,2CACE,WACA,kBACA,MACA,OACA,WACA,YACA,sCAIJ,qBACE,sBAEA,kBACA,SACA,SACA,6BACA,WAEA,UAGF,yBACE,aACA,+BACA,2BACA,WACA,+BAEA,+BACE,gBACA,kBAGF,kCACE,kCACA,cACA,kBACA,kBAEA,+CACE,oCAKN,yBACE,kBACA,kBACA,WACA,YAGF,8BACE,0BACA,kBACA,QACA,SACA,gCACA,kBACA,gBAGF,kCACE,2BACA,iBACA,eACA,qBACA,2C;ACjMJ,OACE,kBACA,gBAEA,mCACE,mCAGF,+FACE,6CAGF,0BACE,sBAEA,sDACE,oBACA,qCACA,sCAMF,0HACE,oBAKF,uJAGE,2BACA,iB;AClCN,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,0CAEA,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,wCAEE,uBACA,yCACA,oBACA,UACA,gBAEA,+CACE,WACA,qBAGF,gDACE,UAEA,wDACE,UAIJ,0DACE,6BAKN,iCACE,kBAEA,wCACE,WACA,qBACA,YACA,aACA,kBACA,+BACA,2BAIJ,wBACE,eACA,q2B;ACnNJ,WACE,aACA,mBACA,WACA,eACA,kBACA,iBAEA,mBACE,6CACA,aACA,mBACA,eACA,mBACA,WACA,eACA,gBACA,6BACA,uDACA,sBACA,gBACA,kCACA,oBACA,0BACA,iBAEA,mFACE,eACA,gBACA,oBAGF,4BACE,aAEA,oCACE,sBACA,iDACA,cACA,eAEA,gDACE,SAKN,0BACE,iCACA,kBACA,UAGF,yBACE,mDAGF,iCACE,cAGF,gCACE,eAIJ,sBACE,mBAGF,2BACE,2BAGF,8BACE,4CACA,WACA,0CACE,0BAGF,qCACE,kBAEA,iDACE,iC;ACrFR,iBACE,kBACA,2BAEA,yBAJF,iBAKI,qCACA,yCACE,qCAEF,8BACE,qCAGF,mCACE,kCACA,2DACE,oCAEF,gDACE,qCAKN,qBACE,2BACA,0CAGF,wBACE,uBACA,0CAGF,+BACE,SACA,sBACA,qBACA,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,sBAKN,+CACE,kBACA,YACA,uBACA,YACA,cACA,8CACA,iBACA,qBACA,oBAEA,kFACE,kDACA,gBAGF,iFACE,WAGF,iFACE,aAGF,kKAEE,UAGF,iFACE,aAKF,4CACE,WACA,cACA,WAGF,kDACE,oBACA,0BACA,oBAEA,iEACE,oBAMJ,4DACE,qCAEA,kEACE,gCAKN,oCACE,yCAEA,gDACE,8CAGF,mDACE,YAIJ,0CACE,wBACA,mBACA,qBACA,kBAEA,sDACE,mBAIJ,gCACE,mBACA,gBACA,uBACA,yDACA,gBACA,oBACA,0BACA,uBACA,aAEA,6CACE,gBACA,uBAGF,yFAEE,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,qBACA,6CAEA,0DACE,0BAKN,4BACE,iDAGF,iGAGE,mCAGF,sCACE,+BAEA,yGACE,WACA,qBACA,iCACA,YAIJ,kDACE,wBAGF,+DACE,qBAGF,kDACE,aAGF,+BACE,gBACA,kBACA,kBACA,eACA,gBACA,0BAEA,uCACE,6BAGF,4CAEE,gBAGF,kDAEE,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,gDACA,iDACA,0DAGF,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,yBAIJ,8EACE,gBAIF,4HAEE,sBAEA,gOACE,sBAIJ,8DACE,aACA,mBACA,uBAEA,oFACE,WACA,mBACA,+CAIJ,gIAEE,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,0CAGF,wGACE,0BACA,oBACA,oBAIJ,8BACE,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,+HAIF,oEACE,iBAKN,2CACE,eACA,iBAEA,0DACE,YAGF,yDACE,gBACA,kBAGF,+DACE,gBAGF,kDACE,WACA,YAIJ,2CACE,eACA,iBACA,gBACA,yBAJF,2CAKI,oBAGF,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,cACA,UACA,+BACA,kBAGF,gEACE,6BAEA,wEACE,UACA,eAUN,gCACE,oBACA,gCAIJ,qBACE,qBAGF,kBACE,oCACA,gCACA,sBACA,eACA,qBAEA,2EAGE,qCAIJ,mCAEE,wBACA,gCACA,qBACA,SACA,gBACA,kBACA,0DACA,eCpzBF,SACE,aACA,qBACA,sBACA,kBAEA,4CACA,wCACA,gDACA,4DACA,0CACA,mBACA,qCACA,iDACA,+CACA,+BACA,8BACA,kCACA,8HAGA,6BACA,4BAEA,wDACA,yDACA,2DACA,4DAEA,0BA7BF,SA8BI,gCAEF,yBAhCF,SAiCI,sBAGF,mBACE,yCAGF,sBACE,0CAGF,mDAEE,UACA,iCACA,8CAEA,iGACE,2BAIJ,iBACE,kBACA,SACA,OAEA,sBAEA,yBAPF,iBAQI,aACA,eAIJ,yBACE,eACA,kBACA,cACA,iBACA,aACA,mBACA,uBACA,mBACA,UACA,uDACA,qBAEA,iCACE,qBAGF,+BACE,uBACA,qBAGF,8CACE,eAIJ,4CACE,4CAGF,6BACE,WACA,aAGF,uBACE,sBACA,yBAFF,uBAGI,wBAIJ,sBAGE,sBAKE,+DACE,wCAIF,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CACE,qDAIA,2DACE,aACA,yBAEA,4EACE,WAMR,iCACE,kBACA,OACA,cACA,aACA,cACA,sBACA,kBACA,wCAEA,aACA,mBACA,uBAEA,WACA,eAEA,UACA,oBACA,4CAEA,8CACE,kBACA,UACA,SACA,mBAGF,6CACE,uBAKF,8GACE,gCAKA,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,kBAKJ,sKAME,qDACA,uDACA,2DACA,6DAGF,8BACE,kCAGF,aACE,gBAEA,6BACE,2BAIJ,8CACE,0e;ACppBF,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,6CAqBA,mE7BzBA,+B6BNF,a7BOI,mBAGA,mB6BEF,oCACE,2BAGF,iCACE,sIAGF,wBApBF,aAqBI,0CACA,2BAEA,gCACE,0CACA,+BAMJ,mCACE,kBACA,+CAEA,2EACE,2BAIJ,yCACE,aAGF,iCACE,WACA,0CACA,gBACA,cACA,aACA,yBACA,sBACA,6BAEA,wDACE,4BAGF,yBAdF,iCAeI,YACA,wBAEA,UAIJ,yBACE,gBAEA,uCACE,mBAIJ,yDAEE,gBAEA,qFACE,uBAEA,yBAHF,qFAII,uBAGF,iHACE,uBAKN,yBACE,+BACE,gBACA,6CACE,sBAEA,yEACE,2DAMR,kDAEE,kBAEA,UACA,mBACA,+CAEA,wEACE,qBACA,UAKF,wEACE,eAGF,kEACE,WACA,kBACA,eACA,kBACA,WACA,YACA,gBACA,WAEA,UACA,4CAEA,gHACE,2BAKF,0GACE,kBAKF,4GACE,eAIJ,kFAEE,2BAOA,wWACE,WAEA,wcACE,WAMR,oBACE,WACA,YACA,aACA,mBACA,uBAEA,yBACE,cACA,gBAGF,sCACE,yBACA,0BAEA,wFAEE,qBAKN,6GAIE,kBACA,0CAEA,iIACE,qBACA,gCACA,WACA,0DACA,gBACA,iBACA,gBACA,4CACA,sBAEA,0WAEE,yDACA,yDAGF,qLACE,2BACA,gDACA,iDACA,0DAKN,0BACE,gBACA,mBACA,6BACA,oBACA,UACA,4BAEA,yBARF,0BASI,iBACA,sBAGF,iEACE,UAEA,sEACE,oBAIJ,iDACE,gBAGF,sCACE,eAGF,+BACE,oBAIJ,sDACE,gBACA,YAGF,0BACE,gBAGF,kDACE,wBAGF,4CACE,uBAGF,+DAEE,iBACA,oBAIA,yCACE,eAEA,+CACE,0BAKN,yCACE,mBAGF,0BA5SF,aA6SI,WACA,+BACA,6CAEA,iCACE,6CAGF,oCACE,gBAGF,qCACE,kEAGF,0NAGE,6CAEA,sRACE,YAKN,yBAxUF,aAyUI,6CAEA,gDACE,+BAGF,sCACE,wGAKF,+CACE,QAIF,iCANF,4BAOI,uBACA,sB;AC9VN,kBACE,wBAEA,kBACA,8BACA,2CACA,UACA,6BACA,6EACA,oCACA,oBAEA,yCACE,0BAEA,wBAGF,yBAlBF,kBAmBI,YACA,cAEA,8CACE,mDAIJ,wBACE,aACA,sBACA,mBAEA,gCACE,iDACA,mCAEA,kCACE,kBAIJ,0BAdF,wBAeI,wBAEA,6CAEA,+CACE,2BAGF,gDACE,4DAIJ,yBACE,gCACE,eACA,iBAKN,2BACE,wBACA,UACA,mBAEA,8DACE,2BAIJ,gCACE,iBACA,cACA,mBACA,qBACA,kBACA,mBACA,gBACA,kBAEA,kBACA,eACA,iBAEA,8BACA,WAEA,oBAEA,yBAnBF,gCAoBI,eACA,YAIJ,yBACE,2CACE,oG;ACpGN,YACE,oBAGE,0BACE,2BAIJ,kBACE,kBACA,YAEA,yBAJF,kBAKI,eAIA,4CACE,kBACA,UACA,UACA,QACA,aAKJ,yCACE,mB;AC5BJ,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,gBAEA,wDAEA,mEACE,aAGF,oCACE,oBAGF,gDACE,2BAGF,6BACE,aACA,mBACA,sBACA,qBAGF,qCACE,cACA,2BACA,aACA,gBACA,wBACA,UACA,kBAEA,yBATF,qCAUI,gB;AClCN,gBACE,gBAEA,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,YACA,gBAGF,iDACE,aAGF,gFAEE,OACA,eACA,gBAGF,qCACE,mBACA,uBAGF,2CACE,gBACA,mBACA,uB;ACxEN,UACE,qBAEA,oDACE,kBACA,mBACA,mCAEA,yBALF,oDAMI,oBAGF,4DACE,eAEA,yBAHF,4DAII,YAIJ,kEACE,UAIJ,wBACE,kBAGF,+BACE,KAEE,WACA,mBAGF,GAEE,aACA,o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BACA,eAGF,gFACE,uBACA,OAGF,8FACE,QAGF,4EACE,oCACA,eACA,qBAEA,8QAGE,qCAIJ,0DACE,yDACA,wCACA,oBACA,oCACA,wJAIF,0FACE,yDAGF,sDACE,kBACA,MACA,OACA,UACA,oBACA,YACA,uBACA,mBAIJ,oBACE,YAEA,kCACE,gBACA,kCACA,uBACA,2BACA,2BACA,8BACA,kBACA,iBACA,mBACA,oEACA,qBAWA,6BATA,yBAbF,kCAcI,gBACA,oBACA,iBACA,sEACA,eAMF,yDACE,2BAIJ,8EAEE,8DAEA,yBAJF,8EAKI,iEAKF,mDACE,eACA,gBAMF,+KACE,kBAIJ,2BACE,cACA,eACA,kBACA,iBACA,oBAKF,kCACE,eACA,mBACA,iBAGF,sCACE,gBACA,cAIJ,kBACE,kBACA,0BACA,OACA,WACA,mCACA,4CACA,gBACA,iBAEA,kBACA,gBAGA,iDAEA,UACA,6BACA,wBACA,6EnChhBA,+BmC6fF,kBnC5fI,mBAGA,mBmC8gBF,8BACE,aAGF,uBACE,UACA,wBAGF,2BACE,cAIJ,sCACE,KACE,UAEF,GACE,gC;AC7iBJ,kBACE,kBACA,MACA,OACA,SACA,QACA,gBACA,WACA,+CAEA,qDACE,gCAGF,yBACE,WACA,kBACA,MACA,OACA,SACA,QACA,+CACA,2BACA,4BACA,sBAEA,4DACE,kEAGF,gDACE,gBAGF,sCACE,yDAEA,yBAHF,sCAII,0DAIJ,qCACE,yDACA,6BACA,sBACA,yBAIJ,gEACE,UAGF,0CACE,qDACA,YACA,qBAGF,kDACE,kBAGF,sCACE,gDACE,6BACA,gBACA,mBACA,6BACA,6CAGF,6HACE,kCAKF,sCADF,6HAEI,iCAGF,sCALF,6HAMI,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,yCACE,kCACA,kGA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ACA,iDANF,StCOI,mBAGA,mBsCDF,iCACE,oBAEA,gDACE,2BAIJ,kCACE,4BACA,2EACA,8DAEA,0CACE,gBAGF,yDACE,iBACA,oCAGF,4CACE,iBAGA,sDACE,cACA,kBAKN,+BACE,UAIJ,cACE,aACA,8BAEA,uBACE,mCACA,SACA,UAEA,4BACE,oBAEA,iCACE,mBAGF,8BACE,aAKN,0BACE,OAIA,kCACE,YACA,iBACA,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,yCACA,uDACA,mCACA,2CACA,8BAEA,6CAEA,oCACE,gBAGF,0BAlBF,aAmBI,8DACA,kBAGF,yBAvBF,aAwBI,YACA,oCAGF,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,8FAEE,mBAIA,yBACE,+DACE,uCAIJ,0DACE,oBACA,+B;AClIN,MACE,YACA,gBACA,gBAEA,0BALF,MAMI,mBAGF,yBATF,MAUI,iCAGF,yBAbF,MAcI,aACA,+BACA,yBAIJ,uBACE,iCACA,oHACE,yBACA,gBAIJ,YACE,gBACA,WACA,kBACA,YACA,kBAEA,gBACE,YACA,gBAGF,yBAZF,YAaI,iCAGF,yBAhBF,YAiBI,gBAGF,0BApBF,YAqBI,WACA,gBAGF,yBAzBF,YA0BI,eACA,OACA,MACA,gCACA,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,mCACA,0CACA,0DAKF,yBADF,aAEI,uCAGF,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/ConnectionStatusOverlay.scss","webpack://telegram-t/./src/components/left/main/LeftMainHeader.scss","webpack://telegram-t/./src/styles/_mixins.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/ChatReportPanel.scss","webpack://telegram-t/./src/components/middle/MiddleHeader.scss","webpack://telegram-t/./src/components/common/EmbeddedMessage.scss","webpack://telegram-t/./src/components/middle/message/ReactionAnimatedEmoji.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/ui/Skeleton.scss","webpack://telegram-t/./src/components/middle/message/Location.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/Reactions.scss","webpack://telegram-t/./src/components/middle/message/_message-content.scss","webpack://telegram-t/./src/components/middle/message/Message.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/AttachMenu.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":[".connection-state-wrapper {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n\n transition: transform 300ms ease, opacity 300ms ease;\n opacity: 1;\n\n &:not(.open) {\n transform: translateY(-3rem);\n opacity: 0;\n }\n\n &:not(.shown) {\n display: none;\n }\n}\n\n#ConnectionStatusOverlay {\n height: 2.9375rem;\n flex: 0 0 auto;\n display: flex;\n align-items: center;\n margin: 0.375rem 0.5rem;\n padding: 0 0.75rem;\n background: var(--color-yellow);\n border-radius: var(--border-radius-default);\n\n &.interactive {\n cursor: pointer;\n }\n\n > .Spinner {\n --spinner-size: 1.75rem;\n }\n\n > .state-text {\n flex: 1;\n color: var(--color-text-lighter);\n font-size: 0.9375rem;\n font-weight: 500;\n padding-bottom: 0.0625rem;\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 .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","@import \"../../../styles/mixins\";\n\n#LeftMainHeader {\n position: relative;\n\n .animated-menu-icon {\n position: absolute;\n\n &,\n &::before,\n &::after {\n width: 1.125rem;\n height: 0.125rem;\n border-radius: 0.125rem;\n background-color: var(--color-text-secondary);\n transition: transform 0.25s;\n transform: rotate(0);\n }\n\n &::before,\n &::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,\n &::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 0.4375rem;\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 .MenuItem.compact .archived-badge {\n background: none;\n padding: 0;\n color: var(--color-text-secondary);\n }\n\n .MenuItem.compact .Switcher {\n transform: scale(0.75);\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",".NewChatButton {\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n transform: translateY(5rem);\n\n transition: transform 0.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 0.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, 0.625rem);\n transform-style: preserve-3d;\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 0.4s ease-out;\n }\n\n .icon-close {\n animation: hide-icon 0.4s forwards ease-out;\n }\n }\n\n &.active {\n .icon-close {\n animation: grow-icon 0.4s ease-out;\n }\n\n .icon-new-chat-filled {\n animation: hide-icon 0.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 > .Transition {\n flex: 1;\n overflow: hidden;\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 /* stylelint-disable-next-line plugin/no-low-performance-animation-properties */\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: 0.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,\n .LeftSearch,\n .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 0.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: 0.25rem;\n }\n }\n}\n",".AudioPlayer {\n display: flex;\n margin-left: auto;\n margin-top: -0.25rem;\n margin-bottom: -0.25rem;\n\n body.animation-level-0 & {\n transition: none !important;\n }\n\n > .Button {\n flex-shrink: 0;\n margin: 0.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: -0.0625rem;\n }\n }\n\n i {\n position: absolute;\n font-size: 1.9375rem;\n margin-top: -0.0625rem;\n\n &.icon-play {\n margin-left: 0.125rem;\n }\n }\n\n .icon-play,\n .icon-pause {\n opacity: 1;\n transform: scale(1);\n transition: opacity 0.4s, transform 0.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(0.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,\n .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.125rem 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 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: 0.9375rem !important;\n line-height: 1.125rem;\n }\n }\n\n .subtitle {\n font-size: 0.8125rem !important;\n color: var(--color-text-secondary);\n line-height: 0.8125rem;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n margin: 0.125rem 0 0;\n\n body.is-ios & {\n font-size: 0.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: -0.1875rem;\n left: 0;\n right: 0;\n height: 0.125rem;\n box-shadow: 0 0.125rem 0.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@media (min-width: 1440px) {\n #Main.right-column-open .MiddleHeader .GroupCallTopPane {\n width: calc(100% - var(--right-column-width));\n }\n}\n",".ChatReportPanel {\n position: absolute;\n left: 0;\n right: 0;\n top: 100%;\n\n display: flex;\n align-items: center;\n margin-left: auto;\n background: var(--color-background);\n padding: 0.375rem 0.8125rem 0.25rem 1rem;\n box-shadow: 0 0.125rem 0.125rem var(--color-light-shadow), inset 0 0.125rem 0.125rem var(--color-light-shadow);\n transform: translate3d(0, 0, 0);\n transition: opacity 0.15s ease, transform var(--layer-transition);\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 padding-right: calc(var(--right-column-width) + 1rem);\n }\n }\n\n .UserReportPanel--Button {\n margin-left: 0.25rem;\n flex: 1 1 50%;\n white-space: nowrap;\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 0.125rem 0.125rem var(--color-light-shadow);\n\n display: flex;\n flex-direction: row-reverse;\n padding-top: 0.375rem;\n padding-bottom: 0.375rem;\n padding-left: max(0.75rem, env(safe-area-inset-left));\n padding-right: max(0.5rem, env(safe-area-inset-right));\n background: var(--color-background);\n\n &::before {\n content: \"\";\n display: block;\n position: absolute;\n top: -0.1875rem;\n left: 0;\n right: 0;\n height: 0.125rem;\n box-shadow: 0 0.125rem 0.125rem var(--color-light-shadow);\n }\n\n .HeaderPinnedMessage {\n max-width: unset;\n margin-top: -0.1875rem;\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: -0.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 position: relative;\n z-index: var(--z-middle-header);\n padding-top: 0.5rem;\n padding-bottom: 0.5rem;\n padding-left: max(1.5rem, env(safe-area-inset-left));\n padding-right: max(0.8125rem, env(safe-area-inset-right));\n\n @media (max-width: 600px) {\n position: relative;\n\n padding-left: max(0.5rem, env(safe-area-inset-left));\n padding-right: max(0.5rem, env(safe-area-inset-right));\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.0625rem;\n }\n }\n\n .status,\n .typing-status {\n display: inline;\n unicode-bidi: plaintext;\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 .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: 0.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,\n .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 .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: 0.25rem 0.8125rem 0.25rem 1rem;\n box-shadow: 0 0.125rem 0.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: -0.1875rem;\n left: 0;\n right: 0;\n height: 0.125rem;\n box-shadow: 0 0.125rem 0.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 0.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 0.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: 0.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: 0.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 .badge-button {\n position: relative;\n overflow: visible;\n }\n\n .badge {\n position: absolute;\n min-width: 1rem;\n height: 1rem;\n background: var(--color-primary);\n border-radius: 0.5rem;\n color: white;\n font-size: 0.75rem;\n line-height: 1rem;\n font-weight: 500;\n text-align: center;\n flex-shrink: 0;\n right: 0;\n top: 0;\n }\n }\n\n .HeaderPinnedMessage-wrapper,\n .HeaderActions {\n .Button {\n margin-left: 0.25rem;\n\n &.tiny {\n margin-right: 0.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) - 0.125rem);\n line-height: 1.125rem;\n margin: 0 -0.25rem 0.0625rem;\n padding: 0.1875rem 0.25rem 0.1875rem 0.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: 0.625rem;\n top: 0.625rem;\n bottom: 0.625rem;\n }\n\n img:not(.emoji) {\n margin-inline-start: 0.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: 0.3125rem;\n bottom: 0.3125rem;\n left: 0.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) - 0.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: 0.25rem;\n margin-left: 0.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 -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: 0.3125rem;\n }\n\n img:not(.emoji) {\n margin-left: 0.125rem;\n }\n\n .message-text {\n margin-inline-start: 0.375rem;\n }\n\n .message-title {\n font-weight: 500;\n color: var(--accent-color);\n }\n }\n}\n",".ReactionAnimatedEmoji {\n position: relative;\n display: flex;\n align-items: center;\n justify-content: center;\n\n &.is-animating {\n // Fix for redundant scroll on iOS\n transform: translateZ(0);\n // Fix for redundant scroll in Firefox\n contain: layout;\n }\n\n .AnimatedSticker {\n position: fixed;\n top: -0.375rem;\n left: -0.375rem;\n pointer-events: none;\n\n &.effect {\n top: -2.5rem;\n left: -2.5rem;\n }\n\n &:not(.open) {\n opacity: 1 !important;\n }\n\n &.closing {\n opacity: 0 !important;\n }\n }\n\n &.in-meta {\n .AnimatedSticker {\n top: -0.4375rem;\n left: -0.4375rem;\n\n &.effect {\n top: -2.5625rem;\n left: -2.5625rem;\n }\n\n // Fix for weird positioning in Chrome\n canvas {\n position: absolute;\n }\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: 0.625rem;\n padding: 0 0.25rem;\n color: white;\n cursor: pointer;\n max-width: 100%;\n user-select: none;\n\n .ReactionAnimatedEmoji {\n width: 1rem;\n height: 1rem;\n margin-right: 0.25rem;\n }\n\n .message-time,\n .message-signature,\n .message-views {\n font-size: 0.75rem;\n white-space: nowrap;\n }\n\n .message-time {\n margin-right: 0.1875rem;\n }\n\n body.is-ios & {\n .message-time {\n margin-right: 0.25rem;\n }\n }\n\n .message-views {\n margin-inline-start: 0.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: 0.25rem;\n right: 0.25rem;\n left: auto;\n height: 1.125rem;\n padding: 0 0.3125rem 0 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: 0.25rem;\n padding: 0 0.375rem 0 0.3125rem;\n }\n\n .is-forwarded.media:not(.text):dir(rtl) &,\n .Message .is-forwarded.custom-shape:dir(rtl) & {\n left: 0.8125rem;\n }\n\n .is-forwarded.media:not(.text) & {\n bottom: 0.9375rem;\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: -0.1875rem;\n font-size: 1.1875rem;\n border-radius: 0.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.25rem;\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.8125rem;\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: 0.125rem;\n width: 1.75rem;\n margin-inline-end: 0.5rem;\n flex-shrink: 0;\n font-weight: 500;\n font-size: 0.875rem;\n text-align: right;\n\n &.limit-width {\n display: inline-flex;\n justify-content: center;\n font-size: 0.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: 0.5rem;\n font-size: 0.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: 0.09s;\n animation-duration: 0.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 0.3s;\n transition-delay: 0.09s;\n }\n\n .poll-line {\n width: 30px;\n height: 35px;\n position: absolute;\n left: -27px;\n bottom: -5px;\n transition: stroke-dashoffset 0.3s, stroke-dasharray 0.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% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\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: 0.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: 0.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: 0.875rem;\n margin-right: 0.5rem;\n margin-top: -2px;\n\n .Avatar {\n border: 0.0625rem solid var(--color-white);\n margin-right: 0;\n box-sizing: content-box;\n\n .Message.own & {\n border: 0.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: 0.75rem;\n transition: color 0.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 0.2s;\n }\n\n .poll-quiz-help {\n margin: -0.625rem 0 -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: 0.625rem;\n }\n}\n",".WebPage {\n margin-top: 0.25rem;\n margin-bottom: 0.125rem;\n padding-left: 0.625rem;\n font-size: calc(var(--message-text-size, 1rem) - 0.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: 0.125rem;\n background: var(--accent-color);\n border-radius: 0.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 &,\n & img,\n &.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: 0.625rem;\n\n &::before {\n left: auto;\n right: 0;\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: 0.25rem 0.5rem;\n margin: 0.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: 0.5rem;\n }\n }\n }\n }\n}\n",".Skeleton {\n position: relative;\n background-color: var(--color-skeleton-background);\n &.round {\n border-radius: 50%;\n }\n\n &.rounded-rect {\n border-radius: 1rem;\n }\n\n &.pulse::before {\n content: \"\";\n display: block;\n width: 100%;\n height: 100%;\n background-color: var(--color-skeleton-foreground);\n animation: skeleton-pulse 2s ease-in-out 0.5s infinite;\n\n @keyframes skeleton-pulse {\n 0% {\n opacity: 1;\n }\n 50% {\n opacity: 0.4;\n }\n 100% {\n opacity: 1;\n }\n }\n }\n\n &.wave::before {\n content: \"\";\n display: block;\n width: 100%;\n height: 100%;\n background: linear-gradient(to right, transparent 0%, var(--color-skeleton-foreground) 50%, transparent 100%);\n animation: skeleton-wave 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;\n\n @keyframes skeleton-wave {\n 0% {\n transform: translateX(-100%);\n }\n 50% {\n transform: translateX(100%);\n }\n 100% {\n transform: translateX(100%);\n }\n }\n }\n}\n",".Location {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n margin-bottom: 0 !important;\n\n .location-accuracy {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n border-radius: 50%;\n\n @keyframes accuracy-wave {\n 0% {\n transform: translate(-50%, -50%) scale(0);\n background-color: var(--color-primary);\n }\n 100% {\n transform: translate(-50%, -50%) scale(1);\n background-color: transparent;\n }\n }\n\n animation: accuracy-wave 5s ease-out infinite forwards;\n }\n\n @keyframes fade-in {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n }\n\n .map-wrapper {\n overflow: hidden;\n position: relative;\n }\n\n .map {\n animation: fade-in 0.3s forwards;\n }\n\n .pin {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -100%);\n animation: fade-in 0.3s forwards;\n\n --pin-color: var(--color-primary);\n }\n\n .geoLive {\n &::before {\n content: \"\";\n position: absolute;\n bottom: 0;\n left: 50%;\n transform: translate(-50%, 50%);\n\n width: 1rem;\n height: 1rem;\n\n background: var(--color-primary);\n border: 2px solid white;\n border-radius: 50%;\n z-index: 3;\n }\n\n .round-pin {\n bottom: 0.5rem;\n }\n }\n\n .direction {\n position: absolute;\n top: 50%;\n left: 50%;\n transition: transform 0.3s ease-out;\n transform: translate(-50%, 0.3125rem) rotate(var(--direction));\n transform-origin: bottom;\n width: 1.5rem;\n height: 2rem;\n clip-path: polygon(50% 100%, 0 0, 100% 0);\n background: radial-gradient(circle, var(--color-primary) -100%, transparent 100%);\n border-radius: 40%;\n z-index: 2;\n }\n\n .location-avatar {\n position: relative;\n overflow: hidden;\n margin-right: 0;\n margin-bottom: 1.3125rem;\n\n z-index: 5;\n }\n\n .venue-icon {\n position: absolute;\n bottom: -0.5rem;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 3rem;\n height: 3rem;\n\n z-index: 5;\n }\n\n .geo {\n height: 2.5rem;\n }\n\n .geoLive,\n .venue {\n filter: drop-shadow(0 0 2px var(--color-default-shadow));\n }\n\n .expired {\n --pin-color: white;\n\n .location-avatar::after {\n content: \"\";\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background-color: rgba(255, 255, 255, 0.3);\n }\n }\n\n .round-pin {\n fill: var(--pin-color);\n\n position: absolute;\n left: 50%;\n bottom: 0;\n transform: translate(-50%, 0);\n width: 5rem;\n\n z-index: 4;\n }\n\n .location-info {\n display: grid;\n grid-template-columns: 1fr auto;\n grid-template-rows: 1fr 1fr;\n width: 100%;\n padding: 0.3125rem 0.5rem 0.375rem;\n\n &-title {\n font-weight: 500;\n grid-area: 1 / 1 / 2 / 2;\n }\n\n &-subtitle {\n color: var(--color-text-secondary);\n line-height: 1;\n font-size: 0.875rem;\n grid-area: 2 / 1 / 2 / 2;\n\n .Message.own & {\n color: var(--color-message-meta-own);\n }\n }\n }\n\n .geo-countdown {\n grid-area: 1 / 2 / 3 / 3;\n position: relative;\n width: 2rem;\n height: 2rem;\n }\n\n .geo-countdown-text {\n color: var(--accent-color);\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n font-size: 0.875rem;\n font-weight: 500;\n }\n\n .geo-countdown-progress {\n stroke: var(--accent-color);\n fill: transparent;\n stroke-width: 2;\n stroke-linecap: round;\n transition: stroke-dashoffset 2s, stroke 0.2s;\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 body.is-ios .Message.own .message-content.has-solid-background :not(.forwarded-message) & {\n margin: -0.3125rem -0.5rem 0.3125rem -0.625rem;\n }\n\n .forwarded-message & {\n margin-bottom: 0.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 &,\n & img,\n & 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: 0.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: 0.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: 0.875rem;\n position: absolute;\n right: 0.1875rem;\n top: 0.1875rem;\n display: block;\n\n &.icon-arrow-right {\n font-size: 0.75rem;\n top: 0.125rem;\n right: 0.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: 0.5625rem 0.25rem 0.5625rem 0.625rem;\n padding-inline-start: 0.625rem;\n padding-inline-end: 0.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: 0.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 0.15s, color 0.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: -0.1875rem;\n left: -0.5625rem;\n width: 0.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 0.15s, filter 0.15s;\n\n .theme-dark #root & {\n filter: invert(0.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 0.3125rem 0.25rem;\n align-items: flex-start;\n color: white;\n background-color: rgba(0, 0, 0, 0.2);\n\n opacity: 0;\n transition: opacity 0.2s ease;\n\n @media (pointer: coarse) {\n opacity: 1 !important;\n }\n\n &:hover {\n background-color: rgba(0, 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: -0.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: 0.375rem -0.5rem -0.375rem;\n }\n\n .message-content.voice & {\n margin-bottom: -0.5rem;\n }\n\n .message-content.audio & {\n margin-bottom: -0.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: 0.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: 0.5rem;\n margin-inline-start: -0.125rem;\n\n .Avatar {\n /* stylelint-disable-next-line plugin/no-low-performance-animation-properties */\n transition: border 0.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: -0.75rem;\n }\n }\n }\n\n &.has-unread .label {\n position: relative;\n\n &::after {\n content: \"\";\n display: inline-block;\n width: 0.5rem;\n height: 0.5rem;\n border-radius: 50%;\n background: var(--accent-color);\n margin-inline-start: 0.75rem;\n }\n }\n\n &.disabled {\n cursor: default;\n pointer-events: none;\n }\n}\n",".Reactions {\n display: flex;\n flex-direction: row;\n width: 100%;\n flex-wrap: wrap;\n margin-top: 0.25rem;\n overflow: visible;\n\n .Button {\n --reaction-background: var(--color-reaction);\n display: flex;\n flex-direction: row;\n height: 1.75rem;\n white-space: nowrap;\n width: auto;\n margin: 0.125rem;\n padding: 0 0.5rem;\n border: 2px solid transparent;\n background-color: var(--reaction-background) !important;\n border-radius: 1.75rem;\n font-weight: 500;\n font-variant-numeric: tabular-nums;\n text-transform: none;\n color: var(--accent-color);\n overflow: visible;\n\n .ReactionAnimatedEmoji, .icon-reaction-filled {\n width: 1.125rem;\n height: 1.125rem;\n margin-right: 0.25rem;\n }\n\n .avatars {\n display: flex;\n\n .Avatar {\n margin: 0 0 0 -0.25rem;\n border: 0.0625rem solid var(--reaction-background);\n width: 1.25rem;\n height: 1.25rem;\n\n &:first-child {\n margin: 0;\n }\n }\n }\n\n &.chosen {\n border-color: var(--accent-color);\n position: relative;\n z-index: 1;\n }\n\n &:hover {\n --reaction-background: var(--hover-color-reaction);\n }\n\n &:first-of-type {\n margin-left: 0;\n }\n\n &:last-of-type {\n margin-right: 0;\n }\n }\n\n &.is-outside {\n margin-top: 0.125rem;\n }\n\n .own &.is-outside {\n flex-direction: row-reverse;\n }\n\n &.is-outside .Button {\n --reaction-background: var(--pattern-color);\n color: white;\n .theme-dark & {\n color: var(--accent-color);\n }\n\n &.chosen {\n border-color: white;\n\n .theme-dark & {\n border-color: var(--accent-color);\n }\n }\n }\n}\n",".message-content {\n position: relative;\n max-width: var(--max-width);\n\n @media (max-width: 600px) {\n max-width: min(29rem, calc(100vw - 6.25rem));\n .MessageList.no-avatars & {\n max-width: min(29rem, calc(100vw - 3.75rem));\n }\n .Message.own & {\n max-width: min(30rem, calc(100vw - 3.75rem));\n }\n\n &.has-action-button {\n max-width: min(29rem, calc(100vw - 7rem));\n .MessageList.no-avatars & {\n max-width: min(29rem, calc(100vw - 4.5rem));\n }\n .Message.own & {\n max-width: min(30rem, calc(100vw - 4.5rem));\n }\n }\n }\n\n img {\n -webkit-touch-callout: none;\n user-select: none;\n }\n\n .emoji {\n -webkit-user-drag: none;\n user-select: text;\n }\n\n .text-content {\n margin: 0;\n word-break: break-word;\n white-space: pre-wrap;\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: 0.375rem;\n bottom: auto !important;\n float: right;\n line-height: 1.35;\n height: calc(var(--message-meta-height, 1rem));\n margin-left: 0.4375rem;\n margin-right: -0.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: 0.25rem;\n }\n\n html[data-message-text-size=\"17\"] & {\n top: 0.4375rem;\n }\n\n html[data-message-text-size=\"18\"] &,\n html[data-message-text-size=\"19\"] & {\n top: 0.5rem;\n }\n\n html[data-message-text-size=\"20\"] & {\n top: 0.5625rem;\n }\n }\n\n &:dir(rtl) {\n & > .MessageMeta {\n float: left;\n margin-left: -0.25rem;\n margin-right: 0.4375rem;\n }\n }\n }\n\n .MessageMeta.reactions-offset {\n position: relative;\n top: 0.375rem;\n bottom: auto !important;\n float: right;\n line-height: 1;\n height: calc(var(--message-meta-height, 1rem));\n margin-left: auto;\n margin-right: -0.5rem;\n align-self: flex-end;\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: 0.25rem;\n }\n\n html[data-message-text-size=\"17\"] & {\n top: 0.4375rem;\n }\n\n html[data-message-text-size=\"18\"] &,\n html[data-message-text-size=\"19\"] & {\n top: 0.5rem;\n }\n\n html[data-message-text-size=\"20\"] & {\n top: 0.5625rem;\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: -0.5rem !important;\n margin-top: -0.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 color: var(--color-text);\n background: #cae3f7;\n border-radius: 0.25rem;\n padding: 0 0.125rem;\n\n .theme-dark & {\n --color-text: #000;\n }\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) - 0.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,\n & > .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: 0.25rem;\n }\n\n .via {\n padding-right: 0.25rem;\n font-weight: 400;\n }\n\n span + .via {\n padding-left: 0.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.125rem;\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,\n &.has-background,\n .is-album & {\n background: var(--background-color);\n }\n\n &.has-solid-background {\n padding: 0.3125rem 0.5rem 0.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: -0.0625rem;\n width: 0.5625rem;\n height: 1.125rem;\n font-size: 1rem !important;\n\n .corner {\n fill: var(--background-color);\n }\n\n .Message.own & {\n /* stylelint-disable-next-line plugin/whole-pixel */\n right: -0.551rem; // This value is correct. Safari fix\n }\n\n .Message:not(.own) & {\n /* stylelint-disable-next-line plugin/whole-pixel */\n left: -0.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: 0.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: 0.3125rem;\n }\n }\n\n &.voice,\n &.audio {\n .message-title,\n .Embedded {\n margin-top: -0.1875rem;\n margin-bottom: 0.1875rem;\n }\n }\n\n &.voice {\n padding: 0.5rem !important;\n\n .Voice + .text-content {\n margin-top: 0.5rem;\n }\n }\n\n &.audio {\n min-width: 20rem;\n padding: 0.5rem 0.5rem 0.8125rem !important;\n\n @media (max-width: 600px) {\n min-width: 17rem;\n }\n\n .Audio + .text-content {\n margin-top: 0.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: 0.125rem;\n max-width: calc(100% - 3rem);\n margin-left: calc(100% - 3rem);\n padding: 0 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.message-content.media,\n.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 &:not(.text) .RoundVideo {\n margin-bottom: 0;\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 0.3s ease, transform 0.3s ease;\n }\n }\n\n .icon-large-play,\n .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 0.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, 0.25);\n color: #fff;\n font-size: 0.75rem;\n position: absolute;\n left: 0.1875rem;\n top: 0.1875rem;\n z-index: 1;\n padding: 0 0.375rem;\n border-radius: 0.75rem;\n line-height: 1.125rem;\n user-select: none;\n }\n\n .message-media-duration .icon-muted {\n vertical-align: -0.1875rem;\n margin-left: 0.375rem;\n font-size: 1.0625rem;\n }\n}\n\n.message-content.custom-shape {\n line-height: 1.2;\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)\n 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: 0.5rem;\n min-width: 10rem;\n @media (max-width: 600px) {\n margin-top: 0.375rem;\n }\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.0625rem;\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.0625rem;\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,\n &:active,\n &:visited {\n text-decoration: underline !important;\n }\n}\n\n.text-entity-code,\n.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 cursor: pointer;\n}\n","@import \"message-content\";\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 --color-reaction: var(--color-message-reaction);\n --hover-color-reaction: var(--color-message-reaction-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(\n var(--meta-safe-area-base) + var(--meta-safe-author-width) + var(--meta-safe-area-extra-width)\n );\n --deleting-translate-x: -50%;\n --select-message-scale: 0.9;\n\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 @media (min-width: 1921px) {\n --max-width: calc(30vw - 1rem);\n }\n @media (max-width: 600px) {\n margin-bottom: 0.25rem;\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 margin-right: 0.3125rem;\n\n @media (max-width: 600px) {\n width: 2.5rem;\n height: 2.5rem;\n }\n }\n\n .quick-reaction {\n cursor: pointer;\n position: absolute;\n right: -0.5rem;\n bottom: -0.375rem;\n display: flex;\n align-items: center;\n justify-content: center;\n transform: scale(1);\n opacity: 0;\n transition: transform 0.2s ease-out, opacity 0.2s ease-out;\n transition-delay: 0.2s;\n\n &.visible {\n opacity: 1 !important;\n }\n\n &:hover {\n transition-delay: unset;\n transform: scale(1.4);\n }\n\n .ReactionStaticEmoji {\n width: 1.125rem;\n }\n }\n\n &.last-in-list .quick-reaction:hover {\n transform: translateY(-0.1875rem) scale(1.4);\n }\n\n &.own .quick-reaction {\n right: auto;\n left: -0.5rem;\n }\n\n &.last-in-group {\n margin-bottom: 0.625rem;\n @media (max-width: 600px) {\n margin-bottom: 0.4375rem;\n }\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 &.has-active-reaction {\n .message-content-wrapper {\n z-index: 1;\n }\n }\n\n &:not(.own) {\n padding-left: 2.5rem;\n\n .no-avatars &,\n &.is-thread-top {\n padding-left: 0;\n }\n\n @media (max-width: 600px) {\n padding-left: 2.875rem;\n\n .no-avatars &,\n &.is-thread-top {\n padding-left: 0.25rem;\n }\n }\n\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 flex-direction: row-reverse;\n --background-color: var(--color-background-own);\n --hover-color: var(--color-reply-own-hover);\n --color-reaction: var(--color-message-reaction-own);\n --hover-color-reaction: var(--color-message-reaction-hover-own);\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 &.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 &.is-deleting {\n > .Avatar,\n > .message-content-wrapper {\n transition: opacity 0.2s ease, transform 0.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 .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 position: absolute;\n .Message.own & {\n background: var(--color-background-own);\n }\n\n .message-select-control {\n position: absolute;\n z-index: 2;\n top: 0.4375rem;\n right: 0.4375rem;\n left: unset;\n }\n\n img,\n 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,\n video {\n transform: scale(var(--select-message-scale));\n }\n }\n }\n\n &.is-selected,\n &.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 .message-content.document {\n padding: 0.25rem 0.5rem !important;\n }\n\n &.last-in-document-group {\n .message-content.document {\n padding-bottom: 0.5rem !important;\n }\n }\n\n &.first-in-document-group {\n .message-content.document {\n padding-top: 0.5rem !important;\n }\n }\n\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.6875rem;\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 &.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 .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 .message-content {\n &.has-replies:not(.custom-shape):not(.has-reactions) .WebPage.with-video .media-inner {\n margin-bottom: 1.5rem !important;\n }\n\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: 0.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, 0.2);\n\n opacity: 0;\n transition: opacity 0.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, 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// 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 .custom-shape .message-action-button {\n bottom: 0.25rem;\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: -0.5rem;\n margin-bottom: 0.5rem;\n\n &::before {\n display: none;\n }\n\n &__button.secondary {\n margin-top: 0.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: 0.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: 0.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: 0.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: 0.25rem;\n text-align: center;\n unicode-bidi: plaintext;\n }\n\n .description {\n font-size: 0.9375rem;\n margin: 0;\n padding: 0;\n list-style: none;\n unicode-bidi: plaintext;\n }\n\n .list-checkmarks {\n font-size: 0.9375rem;\n margin: 0.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: 0.5rem;\n }\n }\n}\n","@import \"../../styles/mixins\";\n\n.MessageList {\n flex: 1;\n width: 100%;\n margin-bottom: 0.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 -webkit-touch-callout: none;\n\n &.select-mode-active {\n user-select: auto;\n -webkit-touch-callout: default;\n }\n }\n\n /* stylelint-disable-next-line plugin/no-low-performance-animation-properties */\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 &.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,\n &.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 body:not(.keyboard-visible) & {\n margin-bottom: calc(4.25rem + env(safe-area-inset-bottom));\n }\n }\n }\n }\n\n .Message,\n .ActionMessage {\n position: relative;\n\n opacity: 1;\n transform: scale(1);\n transition: opacity 0.2s ease, transform 0.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: 0.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,\n &: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) - 0.0625rem);\n font-weight: 500;\n line-height: 1.75;\n padding: 0 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) - 0.125rem);\n line-height: calc(var(--message-text-size, 1rem) + 0.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 0.3s ease;\n\n @media (max-width: 600px) {\n margin-top: 0.5rem;\n margin-bottom: 0.75rem;\n }\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: 0.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: max(1rem, env(safe-area-inset-right));\n opacity: 0;\n transform: translateY(4.5rem);\n transition: transform 0.25s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.2s ease;\n z-index: var(--z-scroll-down-button);\n pointer-events: none;\n\n body.animation-level-0 & {\n transform: none !important;\n\n transition: opacity 0.15s;\n }\n\n @media (max-width: 600px) {\n right: 0.5rem;\n bottom: 4.5rem;\n\n body:not(.keyboard-visible) & {\n bottom: calc(4.5rem + env(safe-area-inset-bottom));\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 0.4375rem;\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.3125rem;\n right: -0.3125rem;\n\n background: var(--color-green);\n color: white;\n\n pointer-events: none;\n\n @media (max-width: 600px) {\n top: -0.6875rem;\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",".AttachMenu {\n align-self: flex-end;\n\n &--button {\n &:focus {\n color: var(--color-primary);\n }\n }\n\n &--menu {\n position: relative;\n top: -3.5rem;\n\n @media (max-width: 600px) {\n top: -2.875rem;\n }\n\n .is-pointer-env & {\n > .backdrop {\n position: absolute;\n top: -1rem;\n left: auto;\n right: 0;\n width: 3.5rem;\n }\n }\n\n\n .media-disabled > button {\n white-space: normal;\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: 0.1875rem 0.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: 0.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: 0.375rem;\n }\n }\n}\n",".ComposerEmbeddedMessage {\n height: 2.625rem;\n /* stylelint-disable-next-line plugin/no-low-performance-animation-properties */\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 /* stylelint-disable-next-line plugin/no-low-performance-animation-properties */\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: 0.125rem;\n bottom: 0.0625rem;\n }\n\n &.with-video .media-inner {\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: 0.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: env(safe-area-inset-bottom);\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 /* stylelint-disable-next-line plugin/no-low-performance-animation-properties */\n width: 1rem;\n transform: scale(0);\n }\n\n to {\n /* stylelint-disable-next-line plugin/no-low-performance-animation-properties */\n width: 3.5rem;\n transform: scale(1);\n }\n }\n\n > .Button {\n flex-shrink: 0;\n margin-left: 0.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-schedule,\n .icon-microphone-alt,\n .icon-check {\n position: absolute;\n }\n\n &:not(:active):not(:focus):not(:hover) {\n .icon-send,\n .icon-schedule,\n .icon-check {\n color: var(--color-primary);\n }\n }\n\n &.cancel {\n position: relative;\n z-index: 1;\n\n &:hover,\n &.active {\n background: var(--color-chat-hover);\n }\n }\n\n &.recording {\n position: relative;\n z-index: 0;\n transition: box-shadow 0.1s;\n }\n\n &.send {\n .icon-send {\n animation: grow-icon 0.4s ease-out;\n }\n\n .icon-microphone-alt,\n .icon-check,\n .icon-schedule {\n animation: hide-icon 0.4s forwards ease-out;\n }\n }\n\n &.schedule {\n .icon-schedule {\n animation: grow-icon 0.4s ease-out;\n }\n\n .icon-microphone-alt,\n .icon-check,\n .icon-send {\n animation: hide-icon 0.4s forwards ease-out;\n }\n }\n\n &.record {\n .icon-microphone-alt {\n animation: grow-icon 0.4s ease-out;\n }\n\n .icon-send,\n .icon-check,\n .icon-schedule {\n animation: hide-icon 0.4s forwards ease-out;\n }\n }\n\n &.edit {\n .icon-check {\n animation: grow-icon 0.4s ease-out;\n }\n\n .icon-send,\n .icon-microphone-alt,\n .icon-schedule {\n animation: hide-icon 0.4s forwards ease-out;\n }\n }\n\n &.not-ready > i {\n animation-duration: 0ms !important;\n }\n\n body.animation-level-0 &,\n body.animation-level-1 & {\n .icon-send,\n .icon-microphone-alt,\n .icon-check,\n .icon-schedule {\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 transform-origin: right;\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 0.4s ease-out;\n }\n\n .icon-keyboard,\n .Spinner {\n animation: hide-icon 0.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 0.4s ease-out;\n }\n\n .icon-keyboard,\n .icon-smile {\n animation: hide-icon 0.4s forwards ease-out;\n }\n }\n\n &.menu-opened {\n .icon-keyboard {\n animation: grow-icon 0.4s ease-out;\n }\n\n .icon-smile,\n .Spinner {\n animation: hide-icon 0.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: -0.1875rem;\n /* stylelint-disable-next-line plugin/whole-pixel */\n right: -0.551rem; // This value is correct. Safari fix\n width: 0.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: -0.5rem;\n }\n\n > .AttachMenu > .Button,\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, + .AttachMenu {\n margin-left: -1rem;\n }\n\n @media (max-width: 600px) {\n width: 2.875rem;\n height: 2.875rem;\n\n + .Button, + .AttachMenu {\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: 0.75rem;\n right: 0.875rem;\n border: 0.1875rem solid var(--color-background);\n box-sizing: content-box;\n width: 0.5rem;\n height: 0.5rem;\n border-radius: 50%;\n background: var(--color-green-darker);\n box-shadow: -0.375rem -0.25rem 0 -0.1875rem var(--color-background);\n @media (max-width: 600px) {\n top: 0.5rem;\n right: 0.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: 0.75rem;\n height: 0.75rem;\n background: var(--color-error);\n border-radius: 0.375rem;\n position: absolute;\n top: 50%;\n margin-top: -0.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)\n calc(0.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\",\n sans-serif;\n }\n\n &.overflown {\n overflow-y: auto;\n overflow-x: hidden;\n }\n\n &.touched,\n &: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,\n &:active,\n &:visited {\n text-decoration: underline !important;\n }\n }\n\n .spoiler {\n background-image: url(\"../../../assets/spoiler-dots-black.png\");\n background-size: auto min(100%, 1.125rem);\n border-radius: 0.5rem;\n padding: 0 0.3125rem 0.125rem 0.3125rem;\n text-shadow: -2px -2px 0 var(--color-background), 2px -2px 0 var(--color-background),\n -2px 2px 0 var(--color-background), 2px 2px 0 var(--color-background);\n }\n\n html.theme-dark & .spoiler {\n background-image: url(\"../../../assets/spoiler-dots-white.png\");\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 /* stylelint-disable-next-line plugin/no-low-performance-animation-properties */\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: 0.8125rem;\n left: 0.9375rem;\n }\n}\n\n.composer-tooltip {\n position: absolute;\n bottom: calc(100% + 0.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: 0.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 body:not(.animation-level-0) #root & {\n transition: background-color 0.2s;\n }\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-image 0.2s;\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 .theme-dark & {\n background-image: url('../../assets/chat-bg-dark.png');\n background-position: top left;\n background-size: 650px;\n background-repeat: repeat;\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 html.theme-light body.animation-level-2 #Main.right-column-open #MiddleColumn:not(.custom-bg-image) &::after {\n transform: scale(0.67) !important;\n }\n }\n\n html.theme-light 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 .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 &,\n &::before {\n transition: none !important;\n }\n }\n }\n\n .message-input-wrapper,\n &::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,\n color 0.15s;\n\n body.animation-level-0 & {\n transition: none !important;\n }\n }\n\n &.hover-disabled,\n &: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,\n &::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 &-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 .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 /* stylelint-disable-next-line plugin/no-low-performance-animation-properties */\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 &: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 &::before {\n content: \"\";\n position: absolute;\n top: -0.5625rem;\n left: 0;\n right: 0;\n height: 1px;\n background: linear-gradient(\n 90deg,\n rgba(255, 255, 255, 0) 0%,\n rgba(255, 255, 255, 0.4) 2%,\n rgba(255, 255, 255, 0.4) 98%,\n rgba(255, 255, 255, 0) 100%\n );\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(\n 90deg,\n rgba(127, 127, 127, 0) 0%,\n rgba(127, 127, 127, 0.4) 2%,\n rgba(127, 127, 127, 0.4) 98%,\n rgba(127, 127, 127, 0) 100%\n );\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 0.25rem 0.5rem 0.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,\n &: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: 0.75rem;\n color: var(--color-text-secondary);\n font-size: 1.5rem;\n transition: color 0.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 0.15s, color 0.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: calc(0.75rem + env(safe-area-inset-bottom));\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 0.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: 0.875rem 0.5rem 0.5rem;\n box-shadow: inset 0 -0.0625rem 0 0 var(--color-background-secondary-accent);\n border-bottom: 0.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 0.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: 0.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: 0.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 padding-right: env(safe-area-inset-right);\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 @media (max-width: 1275px) {\n box-shadow: 0 0.25rem 0.5rem 0.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 > .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 0.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: 0.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 &,\n 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 transform: translate3d(-20vw, 0, 0);\n left: env(safe-area-inset-left) !important;\n width: calc(100vw - env(safe-area-inset-left)) !important;\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":"616.421a1d053cdd90ce3d23.css","mappings":"AAAA,0BACE,kBACA,MACA,OACA,WAEA,mDACA,UAEA,qCACE,4BACA,UAGF,sCACE,aAIJ,yBACE,iBACA,cACA,aACA,mBACA,qBACA,iBACA,+BACA,2CAEA,qCACE,eAGF,kCACE,wBAGF,qCACE,OACA,gCACA,mBACA,gBACA,wBACA,6BACA,mBAGF,yBACE,qCACE,6BAIJ,qCACE,WAGA,YAEA,yCACE,aACA,mBACA,W;AC5DN,gBACE,kBAEA,oCACE,kBAEA,2HAGE,eACA,eACA,sBACA,6CACA,0BACA,oBAGF,uFAEE,kBACA,OACA,WAGF,4CACE,eAGF,2CACE,aAGF,+CACE,yBAEA,uDACE,qEAGF,sDACE,qEAIJ,iDACE,gBAEA,iHAEE,gBAKN,gCACE,iBACA,cACA,iBACA,6BACA,qBACA,mBACA,WACA,kBACA,mBACA,gBACA,kBACA,cAGF,kDACE,gBACA,UACA,kCAGF,4CACE,sBAGF,0CACE,cACA,kBAGF,8BACE,gBACA,yCAEA,gBClFF,+BD8EA,8BC7EE,mBAGA,mBDoFA,wIACE,2B;AEjGN,eACE,kBACA,WACA,YACA,2BAEA,4DAEA,sCACE,0BACA,UAEA,wBAEA,+CACE,UAIJ,wBACE,wBAEA,yBAHF,wBAKI,sCACA,6BAKF,gFAEE,kBAIA,0DACE,iCAGF,gDACE,0CAKF,0CACE,iCAGF,oDACE,0C;ACnDR,iBACE,YACA,kBACA,aACA,sBACA,gBACA,UAEA,6BACE,OACA,gBAGF,8BACE,YACA,aACA,sBACA,gBAEA,gDACE,gBAEA,6BAEA,2DACE,SAIJ,uCACE,2BACA,sBACA,mBACA,gBACA,UAGF,mCACE,cACA,qBACA,sBAEA,wCACE,mBACA,oBAIJ,0CACE,OACA,gBAIJ,+FAGE,YACA,gBAGF,6BACE,kBACA,YACA,UACA,WACA,c;AClEJ,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,sBAIJ,8BACE,kBACA,oBACA,sBAEA,wCACE,oBAIJ,+EAEE,UACA,mBACA,uEAGF,yLAIE,UACA,qBAIJ,4BACE,kBACA,iBAEA,kDACE,kBACA,2BACA,SACA,YACA,WACA,eACA,kBAGF,gHAEE,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,uBACA,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,8BACA,kCACA,qBACA,mBACA,gBACA,uBACA,mBAEA,2CACE,8BACA,qB;AC1KR,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,WAIJ,0BACE,wDACE,8C;ACrFJ,iBACE,kBACA,OACA,QACA,SAEA,aACA,mBACA,iBACA,mCACA,qCACA,yGACA,+BACA,+DAGE,0DACE,aAIJ,0BArBF,iBAsBI,+BACA,+DAEA,yCACE,sDAIJ,0CACE,mBACA,aACA,mB;AC2CJ,cACE,aACA,mBACA,WACA,+CACA,mCACA,kBACA,+BACA,kBACA,qBACA,mDACA,uDAEA,yBAbF,cAcI,kBAEA,kDACA,qDAGF,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,mEPpLN,oIO0LI,oBAIJ,iDACE,8GAEE,UAEA,8JACE,WAnMN,4HAEE,kBACA,SACA,OACA,QACA,gBACA,uDAEA,aACA,2BACA,oBACA,uBACA,mDACA,oDACA,mCAEA,4IACE,WACA,cACA,kBACA,eACA,OACA,QACA,eACA,uDAGF,sKACE,gBACA,sBAIJ,sDACE,mBACA,aACA,qBAEA,8DACE,gBACA,YAGF,8DACE,sBAGF,oEACE,iBAIJ,8DACE,YACA,cACA,iBAEA,sEACE,YACA,eAGF,4EACE,eAIJ,iFACE,aAsIA,0BACE,iEACE,uDAKN,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,oBAIJ,uEAEE,eACA,uBAEA,0BACE,uHACE,kDAKN,qCACE,uBACA,gBACA,uBAEA,0BACE,6DACE,kDAMR,sBACE,qBAEA,wBACA,yBACA,oBAGF,mDAEE,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,mEAIJ,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,8EACE,qDAMR,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,UAIJ,2CACE,kBACA,iBAGF,oCACE,kBACA,eACA,YACA,gCACA,oBACA,WACA,iBACA,iBACA,gBACA,kBACA,cACA,QACA,MAMF,wFACE,mBAEA,kGACE,qBAKN,yBAtjBA,sEAEE,kBACA,SACA,OACA,QACA,gBACA,uDAEA,aACA,2BACA,oBACA,uBACA,mDACA,oDACA,mCAEA,sFACE,WACA,cACA,kBACA,eACA,OACA,QACA,eACA,uDAGF,gHACE,gBACA,sBAIJ,2BACE,mBACA,aACA,qBAEA,mCACE,gBACA,YAGF,mCACE,sBAGF,yCACE,iBAIJ,mCACE,YACA,cACA,iBAEA,2CACE,YACA,eAGF,iDACE,eAIJ,sDACE,cAsfJ,mBACE,KACE,UAEF,GACE,W;ACnkBJ,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,4DACA,6DACA,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,uBACE,kBACA,aACA,mBACA,uBAEA,oCAEE,wBAEA,eAGF,wCACE,eACA,cACA,eACA,oBAEA,+CACE,YACA,aAGF,mDACE,qBAGF,gDACE,qBAKF,gDACE,eACA,gBAEA,uDACE,eACA,gBAIF,uDACE,kB;AC7CR,aACE,kBACA,eACA,SACA,QACA,aACA,mBACA,gCACA,sBACA,iBACA,WACA,eACA,eACA,0CAEA,oCACE,WACA,YACA,oBAGF,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,gBACA,eAGF,yBACE,QAGF,gDACE,oCAGF,oCACE,uBACA,oBACA,sBAEA,iDACE,8BAIJ,6DACE,gBAGF,kEACE,iBAIA,qCACE,SAEF,yCACE,QAMJ,6DACE,WACA,cACA,cAGF,6DACE,YAGF,6DACE,YAGF,6DACE,Y;ACnJF,wBACE,eAGF,kBACE,oB;ACNJ,SACE,aACA,mBACA,eAEA,qBACE,eAGF,iBACE,sBAGF,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,sBAGF,uBACE,WACA,YACA,kBACA,WACA,YACA,sDACA,oBACA,wBAGF,4BACE,iBACA,qBACA,2BACA,UAIA,qCACE,8BAGF,mCACE,0BAKN,iCACE,GACE,UAEF,KACE,W;ACpHJ,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,sFAGE,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;ACzHJ,gBACE,0BACA,gBAGF,sBACE,kBAGE,+CACE,eACA,aAEA,yBAJF,+CAKI,cAIJ,kDACE,kBACA,MACA,qBACA,cACA,oCACA,kDACA,wBACA,gBAEA,uDACE,kB;AC9BV,UACE,kBACA,kDACA,gBACE,kBAGF,uBACE,mBAGF,wBACE,WACA,cACA,WACA,YACA,kDACA,qDAEA,0BACE,GACE,UAEF,IACE,WAEF,KACE,WAKN,uBACE,WACA,cACA,WACA,YACA,6GACA,iEAEA,yBACE,GACE,4BAEF,IACE,2BAEF,KACE,4B;AChDR,UACE,aACA,sBACA,uBACA,2BAEA,6BACE,kBACA,QACA,SACA,gCACA,kBAaA,sDAXA,yBACE,GACE,yCACA,sCAEF,KACE,yCACA,8BAON,mBACE,KACE,UAEF,GACE,WAIJ,uBACE,gBACA,kBAGF,eACE,+BAGF,eACE,kBACA,QACA,SACA,iCACA,+BAEA,kCAIA,2BACE,WACA,kBACA,SACA,SACA,+BAEA,WACA,YAEA,gCACA,sBACA,kBACA,UAGF,8BACE,aAIJ,qBACE,kBACA,QACA,SACA,kCACA,8DACA,wBACA,aACA,YACA,0FACA,iFACA,kBACA,UAGF,2BACE,kBACA,gBACA,eACA,wBAEA,UAGF,sBACE,kBACA,eACA,SACA,gCACA,WACA,YAEA,UAGF,eACE,cAGF,oCAEE,wDAGF,mBACE,mBAEA,2CACE,WACA,kBACA,MACA,OACA,WACA,YACA,sCAIJ,qBACE,sBAEA,kBACA,SACA,SACA,6BACA,WAEA,UAGF,yBACE,aACA,+BACA,2BACA,WACA,+BAEA,+BACE,gBACA,kBAGF,kCACE,kCACA,cACA,kBACA,kBAEA,+CACE,oCAKN,yBACE,kBACA,kBACA,WACA,YAGF,8BACE,0BACA,kBACA,QACA,SACA,gCACA,kBACA,gBAGF,kCACE,2BACA,iBACA,eACA,qBACA,2C;ACjMJ,OACE,kBACA,gBAEA,mCACE,mCAGF,+FACE,6CAGF,0BACE,sBAEA,sDACE,oBACA,qCACA,sCAMF,0HACE,oBAKF,uJAGE,2BACA,iB;AClCN,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,0CAEA,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,wCAEE,uBACA,yCACA,oBACA,UACA,gBAEA,+CACE,WACA,qBAGF,gDACE,UAEA,wDACE,UAIJ,0DACE,6BAKN,iCACE,kBAEA,wCACE,WACA,qBACA,YACA,aACA,kBACA,+BACA,2BAIJ,wBACE,eACA,q2B;ACnNJ,WACE,aACA,mBACA,WACA,eACA,kBACA,iBAEA,mBACE,6CACA,aACA,mBACA,eACA,mBACA,WACA,eACA,gBACA,6BACA,uDACA,sBACA,gBACA,kCACA,oBACA,0BACA,iBAEA,mFACE,eACA,gBACA,oBAGF,4BACE,aAEA,oCACE,sBACA,iDACA,cACA,eAEA,gDACE,SAKN,0BACE,iCACA,kBACA,UAGF,yBACE,mDAGF,iCACE,cAGF,gCACE,eAIJ,sBACE,mBAGF,2BACE,2BAGF,8BACE,4CACA,WACA,0CACE,0BAGF,qCACE,kBAEA,iDACE,iC;ACrFR,iBACE,kBACA,2BAEA,yBAJF,iBAKI,qCACA,yCACE,qCAEF,8BACE,qCAGF,mCACE,kCACA,2DACE,oCAEF,gDACE,qCAKN,qBACE,2BACA,0CAGF,wBACE,uBACA,0CAGF,+BACE,SACA,sBACA,qBACA,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,sBAKN,+CACE,kBACA,YACA,uBACA,YACA,cACA,8CACA,iBACA,qBACA,oBAEA,kFACE,kDACA,gBAGF,iFACE,WAGF,iFACE,aAGF,kKAEE,UAGF,iFACE,aAKF,4CACE,WACA,cACA,WAGF,kDACE,oBACA,0BACA,oBAEA,iEACE,oBAMJ,4DACE,qCAEA,kEACE,gCAKN,oCACE,yCAEA,gDACE,8CAGF,mDACE,YAIJ,0CACE,wBACA,mBACA,qBACA,kBAEA,sDACE,mBAIJ,gCACE,mBACA,gBACA,uBACA,yDACA,gBACA,oBACA,0BACA,uBACA,aAEA,6CACE,gBACA,uBAGF,yFAEE,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,qBACA,6CAEA,0DACE,0BAKN,4BACE,iDAGF,iGAGE,mCAGF,sCACE,+BAEA,yGACE,WACA,qBACA,iCACA,YAIJ,kDACE,wBAGF,+DACE,qBAGF,kDACE,aAGF,+BACE,gBACA,kBACA,kBACA,eACA,gBACA,0BAEA,uCACE,6BAGF,4CAEE,gBAGF,kDAEE,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,gDACA,iDACA,0DAGF,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,yBAIJ,8EACE,gBAIF,4HAEE,sBAEA,gOACE,sBAIJ,8DACE,aACA,mBACA,uBAEA,oFACE,WACA,mBACA,+CAIJ,gIAEE,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,0CAGF,wGACE,0BACA,oBACA,oBAIJ,8BACE,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,+HAIF,oEACE,iBAKN,2CACE,eACA,iBAEA,0DACE,YAGF,yDACE,gBACA,kBAGF,+DACE,gBAGF,kDACE,WACA,YAIJ,2CACE,eACA,iBACA,gBACA,yBAJF,2CAKI,oBAGF,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,cACA,UACA,+BACA,kBAGF,gEACE,6BAEA,wEACE,UACA,eAUN,gCACE,oBACA,gCAIJ,qBACE,qBAGF,kBACE,oCACA,gCACA,sBACA,eACA,qBAEA,2EAGE,qCAIJ,mCAEE,wBACA,gCACA,qBACA,SACA,gBACA,kBACA,0DACA,eCpzBF,SACE,aACA,qBACA,sBACA,kBAEA,4CACA,wCACA,gDACA,4DACA,0CACA,mBACA,qCACA,iDACA,+CACA,+BACA,8BACA,kCACA,8HAGA,6BACA,4BAEA,wDACA,yDACA,2DACA,4DAEA,0BA7BF,SA8BI,gCAEF,yBAhCF,SAiCI,sBAGF,mBACE,yCAGF,sBACE,0CAGF,mDAEE,UACA,iCACA,8CAEA,iGACE,2BAIJ,iBACE,kBACA,SACA,OAEA,sBAEA,yBAPF,iBAQI,aACA,eAIJ,yBACE,eACA,kBACA,cACA,iBACA,aACA,mBACA,uBACA,mBACA,UACA,uDACA,qBAEA,iCACE,qBAGF,+BACE,uBACA,qBAGF,8CACE,eAIJ,4CACE,4CAGF,6BACE,WACA,aAGF,uBACE,sBACA,yBAFF,uBAGI,wBAIJ,sBAGE,sBAKE,+DACE,wCAIF,2DACE,oBAMJ,6CACE,+DAKF,sDACE,UAIJ,mBACE,oBAEA,gEAEE,eAGF,yBARF,mBASI,sBAEA,gEAEE,qBAIJ,sDACE,iEAGF,4DACE,8DACA,iEAGF,sDACE,8DAGF,iCACE,iEAEA,+DACE,+BAKN,aACE,2BACA,gDACA,4CACA,oDACA,gEACA,8CACA,mBACA,wCACA,yCACA,2CACA,oCACA,0CACA,sCACA,8BACA,4BACA,4CAEA,0BAlBF,aAmBI,mBAGF,oDAEE,0DACA,4DACA,8DAGF,yBA7BF,aA8BI,sBAGF,gDACE,kEAGF,sDACE,+DACA,kEAGF,gDACE,+DAGF,2BACE,kEAEA,yDACE,gCACA,6BAMJ,2EAEE,kDACA,UACA,6DACA,wBAIJ,mBACE,mCAGF,oBACE,qCAEA,8BACE,qCAGF,kCACE,qCAEA,4CACE,qCAKN,6BACE,eAEA,yBAHF,6BAII,2CAIA,+GAEE,6BAIJ,mDACE,WACA,kBACA,aACA,gBACA,WACA,YACA,qCAKA,wIACE,qBAIJ,qDACE,UAKF,6CACE,8BAEA,0DACE,uBAEA,sEACE,8BAON,wDACE,8BAIJ,6HAEE,qDAGF,qIAEE,yDAGF,wCACE,eACA,aAIA,kGACE,yDACA,2BACA,qBAEA,yGACE,+BAKN,eACE,kBAEA,uCACE,kBACA,SACA,UACA,UAIJ,oCACE,kBACA,iDACE,uCAGF,4DACE,kBACA,UACA,aACA,eACA,WAGF,kFAEE,iEAIA,wEACE,8BAGF,0GAEE,6CAOJ,4FACE,8BAGF,wEACE,2BAKF,wDACE,gCAIA,+EACE,gCAKF,gFACE,6BAKF,oEACE,iBAGF,6EACE,gBACA,oCACA,qCAGF,uFACE,YAIJ,2DACE,gBAEA,mEACE,oBAGF,4EACE,uCACA,wCAOA,wPACE,gBAEA,sQACE,WACA,cACA,eACA,uBACA,gBACA,oCACA,kBASA,kSACE,mCACA,qCAEA,gTACE,mCACA,2CAYV,4OACE,4CAIA,4PACE,yDACA,gDAKN,uDACE,iBAGF,+CACE,qDAIA,2DACE,aACA,yBAEA,4EACE,WAMR,iCACE,kBACA,OACA,cACA,aACA,cACA,sBACA,kBACA,wCAEA,aACA,mBACA,uBAEA,WACA,eAEA,UACA,oBACA,4CAEA,8CACE,kBACA,UACA,SACA,mBAGF,6CACE,uBAKF,8GACE,gCAKA,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,kBAKJ,sKAME,qDACA,uDACA,2DACA,6DAGF,8BACE,kCAGF,aACE,gBAEA,6BACE,2BAIJ,8CACE,0e;ACppBF,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,6CAqBA,mE7BzBA,+B6BNF,a7BOI,mBAGA,mB6BEF,oCACE,2BAGF,iCACE,sIAGF,wBApBF,aAqBI,0CACA,2BAEA,gCACE,0CACA,+BAMJ,mCACE,kBACA,+CAEA,2EACE,2BAIJ,yCACE,aAGF,iCACE,WACA,0CACA,gBACA,cACA,aACA,yBACA,sBACA,6BAEA,wDACE,4BAGF,yBAdF,iCAeI,YACA,wBAEA,UAIJ,yBACE,gBAEA,uCACE,mBAIJ,yDAEE,gBAEA,qFACE,uBAEA,yBAHF,qFAII,uBAGF,iHACE,uBAKN,yBACE,+BACE,gBACA,6CACE,sBAEA,yEACE,2DAMR,kDAEE,kBAEA,UACA,mBACA,+CAEA,wEACE,qBACA,UAKF,wEACE,eAGF,kEACE,WACA,kBACA,eACA,kBACA,WACA,YACA,gBACA,WAEA,UACA,4CAEA,gHACE,2BAKF,0GACE,kBAKF,4GACE,eAIJ,kFAEE,2BAOA,wWACE,WAEA,wcACE,WAMR,oBACE,WACA,YACA,aACA,mBACA,uBAEA,yBACE,cACA,gBAGF,sCACE,yBACA,0BAEA,wFAEE,qBAKN,6GA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BACA,iDACA,kBACA,UAEA,+BACE,kBACA,kBAEA,gBACA,eACA,eACA,yBACA,0BAEA,uCACE,6BAIJ,yBAzBF,iBA0BI,iCAIJ,uBACE,aAEA,gCACE,kBACA,uBACA,qBAGF,0EAEE,cACA,2BACA,aACA,cACA,SACA,UACA,oBAEA,kIACE,mCAGF,4LACE,kBAGF,yBAlBF,0EAmBI,eACA,gBAEA,4LACE,wBAIJ,oGACE,sCAGA,gOACE,yCAIJ,8HACE,WACA,kBACA,WACA,cACA,8CACA,uBACA,YACA,aACA,kBACA,qCACA,mEACA,yBAZF,8HAaI,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,+HAEA,gBACA,kBACA,iFACA,uBACA,mBACA,0CAEA,4LAEE,gHAIF,wFACE,gBACA,kBAKA,4OACE,aAIJ,kGACE,oBAIJ,4JAEE,kBACA,gCACA,oBACA,uBACA,mBACA,mBACA,0CACA,8DACA,YACA,mBACA,gBACA,uBACA,eAGF,gFACE,uBACA,OAGF,8FACE,QAGF,4EACE,oCACA,eACA,qBAEA,8QAGE,qCAIJ,0DACE,yDACA,wCACA,oBACA,oCACA,wJAIF,0FACE,yDAGF,sDACE,kBACA,MACA,OACA,UACA,oBACA,YACA,uBACA,mBAIJ,oBACE,YAEA,kCACE,gBACA,kCACA,uBACA,2BACA,2BACA,8BACA,kBACA,iBACA,mBACA,oEACA,qBAWA,6BATA,yBAbF,kCAcI,gBACA,oBACA,iBACA,sEACA,eAMF,yDACE,2BAIJ,8EAEE,8DAEA,yBAJF,8EAKI,iEAKF,mDACE,eACA,gBAMF,+KACE,kBAIJ,2BACE,cACA,eACA,kBACA,iBACA,oBAKF,kCACE,eACA,mBACA,iBAGF,sCACE,gBACA,cAIJ,kBACE,kBACA,0BACA,OACA,WACA,mCACA,4CACA,gBACA,iBAEA,kBACA,gBAGA,iDAEA,UACA,6BACA,wBACA,6EnChhBA,+BmC6fF,kBnC5fI,mBAGA,mBmC8gBF,8BACE,aAGF,uBACE,UACA,wBAGF,2BACE,cAIJ,sCACE,KACE,UAEF,GACE,gC;AC7iBJ,kBACE,kBACA,MACA,OACA,SACA,QACA,gBACA,WACA,+CAEA,qDACE,gCAGF,yBACE,WACA,kBACA,MACA,OACA,SACA,QACA,+CACA,2BACA,4BACA,sBAEA,4DACE,kEAGF,gDACE,gBAGF,sCACE,yDAEA,yBAHF,sCAII,0DAIJ,yEACE,yDACA,6BACA,sBACA,yBAIJ,gEACE,UAGF,0CACE,qDACA,YACA,qBAGF,kDACE,kBAGF,sCACE,gDACE,6BACA,gBACA,mBACA,6BACA,6CAGF,6HACE,kCAKF,sCADF,6HAEI,iCAGF,sCALF,6HAMI,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,yCACE,kCACA,kGAEA,iDACE,mCACA,8CAIA,wIAEE,2BAKN,+EAEE,UACA,4CAEA,6HACE,2BAIJ,gCACE,UACA,mBACA,gHAGA,uDACE,2BAIJ,2EAEE,oBAIA,6DACE,SAGF,qDACE,6FACA,yDAEA,6DACE,sCAIJ,2DACE,yBAEA,yBAHF,2DAII,0BAIJ,uGAEE,UAGF,4CACE,qBACA,qBAKN,kCACE,oBACA,8CAEA,iEACE,UACA,4CAEA,wFACE,2BAIJ,yDACE,2BAGF,8CACE,kDACA,oBAEA,6EACE,UAIJ,wCACE,WACA,aACA,4CACA,mCACA,kCACA,kBACA,iDAIJ,oCACE,WACA,0CACA,eACA,kBACA,aACA,qBACA,+BAEA,+BAEA,uDAEA,2DACE,2BAGF,0BAjBF,oCAkBI,6CAEA,4DACE,mEAIJ,yBAz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BACE,YACA,gBACA,kBAEA,sBACE,YACA,gB;ACPJ,aACE,kBACA,MACA,QACA,gCACA,YACA,yCACA,uDACA,mCACA,2CACA,8BAEA,6CAEA,oCACE,gBAGF,0BAlBF,aAmBI,8DACA,kBAGF,yBAvBF,aAwBI,YACA,oCAGF,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,8FAEE,mBAIA,yBACE,+DACE,uCAIJ,0DACE,oBACA,+B;AClIN,MACE,YACA,gBACA,gBAEA,0BALF,MAMI,mBAGF,yBATF,MAUI,iCAGF,yBAbF,MAcI,aACA,+BACA,yBAIJ,uBACE,iCACA,oHACE,yBACA,gBAIJ,YACE,gBACA,WACA,kBACA,YACA,kBAEA,gBACE,YACA,gBAGF,yBAZF,YAaI,iCAGF,yBAhBF,YAiBI,gBAGF,0BApBF,YAqBI,WACA,gBAGF,yBAzBF,YA0BI,eACA,OACA,MACA,gCACA,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,mCACA,0CACA,0DAKF,yBADF,aAEI,uCAGF,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/ConnectionStatusOverlay.scss","webpack://telegram-t/./src/components/left/main/LeftMainHeader.scss","webpack://telegram-t/./src/styles/_mixins.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/ChatReportPanel.scss","webpack://telegram-t/./src/components/middle/MiddleHeader.scss","webpack://telegram-t/./src/components/common/EmbeddedMessage.scss","webpack://telegram-t/./src/components/middle/message/ReactionAnimatedEmoji.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/ui/Skeleton.scss","webpack://telegram-t/./src/components/middle/message/Location.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/Reactions.scss","webpack://telegram-t/./src/components/middle/message/_message-content.scss","webpack://telegram-t/./src/components/middle/message/Message.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/AttachMenu.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":[".connection-state-wrapper {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n\n transition: transform 300ms ease, opacity 300ms ease;\n opacity: 1;\n\n &:not(.open) {\n transform: translateY(-3rem);\n opacity: 0;\n }\n\n &:not(.shown) {\n display: none;\n }\n}\n\n#ConnectionStatusOverlay {\n height: 2.9375rem;\n flex: 0 0 auto;\n display: flex;\n align-items: center;\n margin: 0.375rem 0.5rem;\n padding: 0 0.75rem;\n background: var(--color-yellow);\n border-radius: var(--border-radius-default);\n\n &.interactive {\n cursor: pointer;\n }\n\n > .Spinner {\n --spinner-size: 1.75rem;\n }\n\n > .state-text {\n flex: 1;\n color: var(--color-text-lighter);\n font-size: 0.9375rem;\n font-weight: 500;\n padding-bottom: 0.0625rem;\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 .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","@import \"../../../styles/mixins\";\n\n#LeftMainHeader {\n position: relative;\n\n .animated-menu-icon {\n position: absolute;\n\n &,\n &::before,\n &::after {\n width: 1.125rem;\n height: 0.125rem;\n border-radius: 0.125rem;\n background-color: var(--color-text-secondary);\n transition: transform 0.25s;\n transform: rotate(0);\n }\n\n &::before,\n &::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,\n &::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 0.4375rem;\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 .MenuItem.compact .archived-badge {\n background: none;\n padding: 0;\n color: var(--color-text-secondary);\n }\n\n .MenuItem.compact .Switcher {\n transform: scale(0.75);\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",".NewChatButton {\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n transform: translateY(5rem);\n\n transition: transform 0.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 0.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, 0.625rem);\n transform-style: preserve-3d;\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 0.4s ease-out;\n }\n\n .icon-close {\n animation: hide-icon 0.4s forwards ease-out;\n }\n }\n\n &.active {\n .icon-close {\n animation: grow-icon 0.4s ease-out;\n }\n\n .icon-new-chat-filled {\n animation: hide-icon 0.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 > .Transition {\n flex: 1;\n overflow: hidden;\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 /* stylelint-disable-next-line plugin/no-low-performance-animation-properties */\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: 0.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,\n .LeftSearch,\n .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 0.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: 0.25rem;\n }\n }\n}\n",".AudioPlayer {\n display: flex;\n margin-left: auto;\n margin-top: -0.25rem;\n margin-bottom: -0.25rem;\n\n body.animation-level-0 & {\n transition: none !important;\n }\n\n > .Button {\n flex-shrink: 0;\n margin: 0.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: -0.0625rem;\n }\n }\n\n i {\n position: absolute;\n font-size: 1.9375rem;\n margin-top: -0.0625rem;\n\n &.icon-play {\n margin-left: 0.125rem;\n }\n }\n\n .icon-play,\n .icon-pause {\n opacity: 1;\n transform: scale(1);\n transition: opacity 0.4s, transform 0.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(0.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,\n .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.125rem 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 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: 0.9375rem !important;\n line-height: 1.125rem;\n }\n }\n\n .subtitle {\n font-size: 0.8125rem !important;\n color: var(--color-text-secondary);\n line-height: 0.8125rem;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n margin: 0.125rem 0 0;\n\n body.is-ios & {\n font-size: 0.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: -0.1875rem;\n left: 0;\n right: 0;\n height: 0.125rem;\n box-shadow: 0 0.125rem 0.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@media (min-width: 1440px) {\n #Main.right-column-open .MiddleHeader .GroupCallTopPane {\n width: calc(100% - var(--right-column-width));\n }\n}\n",".ChatReportPanel {\n position: absolute;\n left: 0;\n right: 0;\n top: 100%;\n\n display: flex;\n align-items: center;\n margin-left: auto;\n background: var(--color-background);\n padding: 0.375rem 0.8125rem 0.25rem 1rem;\n box-shadow: 0 0.125rem 0.125rem var(--color-light-shadow), inset 0 0.125rem 0.125rem var(--color-light-shadow);\n transform: translate3d(0, 0, 0);\n transition: opacity 0.15s ease, transform var(--layer-transition);\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 padding-right: calc(var(--right-column-width) + 1rem);\n }\n }\n\n .UserReportPanel--Button {\n margin-left: 0.25rem;\n flex: 1 1 50%;\n white-space: nowrap;\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 0.125rem 0.125rem var(--color-light-shadow);\n\n display: flex;\n flex-direction: row-reverse;\n padding-top: 0.375rem;\n padding-bottom: 0.375rem;\n padding-left: max(0.75rem, env(safe-area-inset-left));\n padding-right: max(0.5rem, env(safe-area-inset-right));\n background: var(--color-background);\n\n &::before {\n content: \"\";\n display: block;\n position: absolute;\n top: -0.1875rem;\n left: 0;\n right: 0;\n height: 0.125rem;\n box-shadow: 0 0.125rem 0.125rem var(--color-light-shadow);\n }\n\n .HeaderPinnedMessage {\n max-width: unset;\n margin-top: -0.1875rem;\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: -0.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 position: relative;\n z-index: var(--z-middle-header);\n padding-top: 0.5rem;\n padding-bottom: 0.5rem;\n padding-left: max(1.5rem, env(safe-area-inset-left));\n padding-right: max(0.8125rem, env(safe-area-inset-right));\n\n @media (max-width: 600px) {\n position: relative;\n\n padding-left: max(0.5rem, env(safe-area-inset-left));\n padding-right: max(0.5rem, env(safe-area-inset-right));\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.0625rem;\n }\n }\n\n .status,\n .typing-status {\n display: inline;\n unicode-bidi: plaintext;\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 .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: 0.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,\n .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 .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: 0.25rem 0.8125rem 0.25rem 1rem;\n box-shadow: 0 0.125rem 0.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: -0.1875rem;\n left: 0;\n right: 0;\n height: 0.125rem;\n box-shadow: 0 0.125rem 0.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 0.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 0.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: 0.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: 0.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 .badge-button {\n position: relative;\n overflow: visible;\n }\n\n .badge {\n position: absolute;\n min-width: 1rem;\n height: 1rem;\n background: var(--color-primary);\n border-radius: 0.5rem;\n color: white;\n font-size: 0.75rem;\n line-height: 1rem;\n font-weight: 500;\n text-align: center;\n flex-shrink: 0;\n right: 0;\n top: 0;\n }\n }\n\n .HeaderPinnedMessage-wrapper,\n .HeaderActions {\n .Button {\n margin-left: 0.25rem;\n\n &.tiny {\n margin-right: 0.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) - 0.125rem);\n line-height: 1.125rem;\n margin: 0 -0.25rem 0.0625rem;\n padding: 0.1875rem 0.25rem 0.1875rem 0.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: 0.625rem;\n top: 0.625rem;\n bottom: 0.625rem;\n }\n\n img:not(.emoji) {\n margin-inline-start: 0.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: 0.3125rem;\n bottom: 0.3125rem;\n left: 0.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) - 0.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: 0.25rem;\n margin-left: 0.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 -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: 0.3125rem;\n }\n\n img:not(.emoji) {\n margin-left: 0.125rem;\n }\n\n .message-text {\n margin-inline-start: 0.375rem;\n }\n\n .message-title {\n font-weight: 500;\n color: var(--accent-color);\n }\n }\n}\n",".ReactionAnimatedEmoji {\n position: relative;\n display: flex;\n align-items: center;\n justify-content: center;\n\n &.is-animating {\n // Fix for redundant scroll on iOS\n transform: translateZ(0);\n // Fix for redundant scroll in Firefox\n contain: layout;\n }\n\n .AnimatedSticker {\n position: fixed;\n top: -0.375rem;\n left: -0.375rem;\n pointer-events: none;\n\n &.effect {\n top: -2.5rem;\n left: -2.5rem;\n }\n\n &:not(.open) {\n opacity: 1 !important;\n }\n\n &.closing {\n opacity: 0 !important;\n }\n }\n\n &.in-meta {\n .AnimatedSticker {\n top: -0.4375rem;\n left: -0.4375rem;\n\n &.effect {\n top: -2.5625rem;\n left: -2.5625rem;\n }\n\n // Fix for weird positioning in Chrome\n canvas {\n position: absolute;\n }\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: 0.625rem;\n padding: 0 0.25rem;\n color: white;\n cursor: pointer;\n max-width: 100%;\n user-select: none;\n\n .ReactionAnimatedEmoji {\n width: 1rem;\n height: 1rem;\n margin-right: 0.25rem;\n }\n\n .message-time,\n .message-signature,\n .message-views {\n font-size: 0.75rem;\n white-space: nowrap;\n }\n\n .message-time {\n margin-right: 0.1875rem;\n }\n\n body.is-ios & {\n .message-time {\n margin-right: 0.25rem;\n }\n }\n\n .message-views {\n margin-inline-start: 0.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: 0.25rem;\n right: 0.25rem;\n left: auto;\n height: 1.125rem;\n padding: 0 0.3125rem 0 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: 0.25rem;\n padding: 0 0.375rem 0 0.3125rem;\n }\n\n .is-forwarded.media:not(.text):dir(rtl) &,\n .Message .is-forwarded.custom-shape:dir(rtl) & {\n left: 0.8125rem;\n }\n\n .is-forwarded.media:not(.text) & {\n bottom: 0.9375rem;\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: -0.1875rem;\n font-size: 1.1875rem;\n border-radius: 0.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.25rem;\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.8125rem;\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: 0.125rem;\n width: 1.75rem;\n margin-inline-end: 0.5rem;\n flex-shrink: 0;\n font-weight: 500;\n font-size: 0.875rem;\n text-align: right;\n\n &.limit-width {\n display: inline-flex;\n justify-content: center;\n font-size: 0.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: 0.5rem;\n font-size: 0.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: 0.09s;\n animation-duration: 0.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 0.3s;\n transition-delay: 0.09s;\n }\n\n .poll-line {\n width: 30px;\n height: 35px;\n position: absolute;\n left: -27px;\n bottom: -5px;\n transition: stroke-dashoffset 0.3s, stroke-dasharray 0.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% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\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: 0.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: 0.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: 0.875rem;\n margin-right: 0.5rem;\n margin-top: -2px;\n\n .Avatar {\n border: 0.0625rem solid var(--color-white);\n margin-right: 0;\n box-sizing: content-box;\n\n .Message.own & {\n border: 0.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: 0.75rem;\n transition: color 0.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 0.2s;\n }\n\n .poll-quiz-help {\n margin: -0.625rem 0 -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: 0.625rem;\n }\n}\n",".WebPage {\n margin-top: 0.25rem;\n margin-bottom: 0.125rem;\n padding-left: 0.625rem;\n font-size: calc(var(--message-text-size, 1rem) - 0.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: 0.125rem;\n background: var(--accent-color);\n border-radius: 0.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 &,\n & img,\n &.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: 0.625rem;\n\n &::before {\n left: auto;\n right: 0;\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: 0.25rem 0.5rem;\n margin: 0.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: 0.5rem;\n }\n }\n }\n }\n}\n",".Skeleton {\n position: relative;\n background-color: var(--color-skeleton-background);\n &.round {\n border-radius: 50%;\n }\n\n &.rounded-rect {\n border-radius: 1rem;\n }\n\n &.pulse::before {\n content: \"\";\n display: block;\n width: 100%;\n height: 100%;\n background-color: var(--color-skeleton-foreground);\n animation: skeleton-pulse 2s ease-in-out 0.5s infinite;\n\n @keyframes skeleton-pulse {\n 0% {\n opacity: 1;\n }\n 50% {\n opacity: 0.4;\n }\n 100% {\n opacity: 1;\n }\n }\n }\n\n &.wave::before {\n content: \"\";\n display: block;\n width: 100%;\n height: 100%;\n background: linear-gradient(to right, transparent 0%, var(--color-skeleton-foreground) 50%, transparent 100%);\n animation: skeleton-wave 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;\n\n @keyframes skeleton-wave {\n 0% {\n transform: translateX(-100%);\n }\n 50% {\n transform: translateX(100%);\n }\n 100% {\n transform: translateX(100%);\n }\n }\n }\n}\n",".Location {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n margin-bottom: 0 !important;\n\n .location-accuracy {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n border-radius: 50%;\n\n @keyframes accuracy-wave {\n 0% {\n transform: translate(-50%, -50%) scale(0);\n background-color: var(--color-primary);\n }\n 100% {\n transform: translate(-50%, -50%) scale(1);\n background-color: transparent;\n }\n }\n\n animation: accuracy-wave 5s ease-out infinite forwards;\n }\n\n @keyframes fade-in {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n }\n\n .map-wrapper {\n overflow: hidden;\n position: relative;\n }\n\n .map {\n animation: fade-in 0.3s forwards;\n }\n\n .pin {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -100%);\n animation: fade-in 0.3s forwards;\n\n --pin-color: var(--color-primary);\n }\n\n .geoLive {\n &::before {\n content: \"\";\n position: absolute;\n bottom: 0;\n left: 50%;\n transform: translate(-50%, 50%);\n\n width: 1rem;\n height: 1rem;\n\n background: var(--color-primary);\n border: 2px solid white;\n border-radius: 50%;\n z-index: 3;\n }\n\n .round-pin {\n bottom: 0.5rem;\n }\n }\n\n .direction {\n position: absolute;\n top: 50%;\n left: 50%;\n transition: transform 0.3s ease-out;\n transform: translate(-50%, 0.3125rem) rotate(var(--direction));\n transform-origin: bottom;\n width: 1.5rem;\n height: 2rem;\n clip-path: polygon(50% 100%, 0 0, 100% 0);\n background: radial-gradient(circle, var(--color-primary) -100%, transparent 100%);\n border-radius: 40%;\n z-index: 2;\n }\n\n .location-avatar {\n position: relative;\n overflow: hidden;\n margin-right: 0;\n margin-bottom: 1.3125rem;\n\n z-index: 5;\n }\n\n .venue-icon {\n position: absolute;\n bottom: -0.5rem;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 3rem;\n height: 3rem;\n\n z-index: 5;\n }\n\n .geo {\n height: 2.5rem;\n }\n\n .geoLive,\n .venue {\n filter: drop-shadow(0 0 2px var(--color-default-shadow));\n }\n\n .expired {\n --pin-color: white;\n\n .location-avatar::after {\n content: \"\";\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background-color: rgba(255, 255, 255, 0.3);\n }\n }\n\n .round-pin {\n fill: var(--pin-color);\n\n position: absolute;\n left: 50%;\n bottom: 0;\n transform: translate(-50%, 0);\n width: 5rem;\n\n z-index: 4;\n }\n\n .location-info {\n display: grid;\n grid-template-columns: 1fr auto;\n grid-template-rows: 1fr 1fr;\n width: 100%;\n padding: 0.3125rem 0.5rem 0.375rem;\n\n &-title {\n font-weight: 500;\n grid-area: 1 / 1 / 2 / 2;\n }\n\n &-subtitle {\n color: var(--color-text-secondary);\n line-height: 1;\n font-size: 0.875rem;\n grid-area: 2 / 1 / 2 / 2;\n\n .Message.own & {\n color: var(--color-message-meta-own);\n }\n }\n }\n\n .geo-countdown {\n grid-area: 1 / 2 / 3 / 3;\n position: relative;\n width: 2rem;\n height: 2rem;\n }\n\n .geo-countdown-text {\n color: var(--accent-color);\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n font-size: 0.875rem;\n font-weight: 500;\n }\n\n .geo-countdown-progress {\n stroke: var(--accent-color);\n fill: transparent;\n stroke-width: 2;\n stroke-linecap: round;\n transition: stroke-dashoffset 2s, stroke 0.2s;\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 body.is-ios .Message.own .message-content.has-solid-background :not(.forwarded-message) & {\n margin: -0.3125rem -0.5rem 0.3125rem -0.625rem;\n }\n\n .forwarded-message & {\n margin-bottom: 0.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 &,\n & img,\n & 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: 0.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: 0.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: 0.875rem;\n position: absolute;\n right: 0.1875rem;\n top: 0.1875rem;\n display: block;\n\n &.icon-arrow-right {\n font-size: 0.75rem;\n top: 0.125rem;\n right: 0.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: 0.5625rem 0.25rem 0.5625rem 0.625rem;\n padding-inline-start: 0.625rem;\n padding-inline-end: 0.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: 0.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 0.15s, color 0.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: -0.1875rem;\n left: -0.5625rem;\n width: 0.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 0.15s, filter 0.15s;\n\n .theme-dark #root & {\n filter: invert(0.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 0.3125rem 0.25rem;\n align-items: flex-start;\n color: white;\n background-color: rgba(0, 0, 0, 0.2);\n\n opacity: 0;\n transition: opacity 0.2s ease;\n\n @media (pointer: coarse) {\n opacity: 1 !important;\n }\n\n &:hover {\n background-color: rgba(0, 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: -0.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: 0.375rem -0.5rem -0.375rem;\n }\n\n .message-content.voice & {\n margin-bottom: -0.5rem;\n }\n\n .message-content.audio & {\n margin-bottom: -0.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: 0.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: 0.5rem;\n margin-inline-start: -0.125rem;\n\n .Avatar {\n /* stylelint-disable-next-line plugin/no-low-performance-animation-properties */\n transition: border 0.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: -0.75rem;\n }\n }\n }\n\n &.has-unread .label {\n position: relative;\n\n &::after {\n content: \"\";\n display: inline-block;\n width: 0.5rem;\n height: 0.5rem;\n border-radius: 50%;\n background: var(--accent-color);\n margin-inline-start: 0.75rem;\n }\n }\n\n &.disabled {\n cursor: default;\n pointer-events: none;\n }\n}\n",".Reactions {\n display: flex;\n flex-direction: row;\n width: 100%;\n flex-wrap: wrap;\n margin-top: 0.25rem;\n overflow: visible;\n\n .Button {\n --reaction-background: var(--color-reaction);\n display: flex;\n flex-direction: row;\n height: 1.75rem;\n white-space: nowrap;\n width: auto;\n margin: 0.125rem;\n padding: 0 0.5rem;\n border: 2px solid transparent;\n background-color: var(--reaction-background) !important;\n border-radius: 1.75rem;\n font-weight: 500;\n font-variant-numeric: tabular-nums;\n text-transform: none;\n color: var(--accent-color);\n overflow: visible;\n\n .ReactionAnimatedEmoji, .icon-reaction-filled {\n width: 1.125rem;\n height: 1.125rem;\n margin-right: 0.25rem;\n }\n\n .avatars {\n display: flex;\n\n .Avatar {\n margin: 0 0 0 -0.25rem;\n border: 0.0625rem solid var(--reaction-background);\n width: 1.25rem;\n height: 1.25rem;\n\n &:first-child {\n margin: 0;\n }\n }\n }\n\n &.chosen {\n border-color: var(--accent-color);\n position: relative;\n z-index: 1;\n }\n\n &:hover {\n --reaction-background: var(--hover-color-reaction);\n }\n\n &:first-of-type {\n margin-left: 0;\n }\n\n &:last-of-type {\n margin-right: 0;\n }\n }\n\n &.is-outside {\n margin-top: 0.125rem;\n }\n\n .own &.is-outside {\n flex-direction: row-reverse;\n }\n\n &.is-outside .Button {\n --reaction-background: var(--pattern-color);\n color: white;\n .theme-dark & {\n color: var(--accent-color);\n }\n\n &.chosen {\n border-color: white;\n\n .theme-dark & {\n border-color: var(--accent-color);\n }\n }\n }\n}\n",".message-content {\n position: relative;\n max-width: var(--max-width);\n\n @media (max-width: 600px) {\n max-width: min(29rem, calc(100vw - 6.25rem));\n .MessageList.no-avatars & {\n max-width: min(29rem, calc(100vw - 3.75rem));\n }\n .Message.own & {\n max-width: min(30rem, calc(100vw - 3.75rem));\n }\n\n &.has-action-button {\n max-width: min(29rem, calc(100vw - 7rem));\n .MessageList.no-avatars & {\n max-width: min(29rem, calc(100vw - 4.5rem));\n }\n .Message.own & {\n max-width: min(30rem, calc(100vw - 4.5rem));\n }\n }\n }\n\n img {\n -webkit-touch-callout: none;\n user-select: none;\n }\n\n .emoji {\n -webkit-user-drag: none;\n user-select: text;\n }\n\n .text-content {\n margin: 0;\n word-break: break-word;\n white-space: pre-wrap;\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: 0.375rem;\n bottom: auto !important;\n float: right;\n line-height: 1.35;\n height: calc(var(--message-meta-height, 1rem));\n margin-left: 0.4375rem;\n margin-right: -0.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: 0.25rem;\n }\n\n html[data-message-text-size=\"17\"] & {\n top: 0.4375rem;\n }\n\n html[data-message-text-size=\"18\"] &,\n html[data-message-text-size=\"19\"] & {\n top: 0.5rem;\n }\n\n html[data-message-text-size=\"20\"] & {\n top: 0.5625rem;\n }\n }\n\n &:dir(rtl) {\n & > .MessageMeta {\n float: left;\n margin-left: -0.25rem;\n margin-right: 0.4375rem;\n }\n }\n }\n\n .MessageMeta.reactions-offset {\n position: relative;\n top: 0.375rem;\n bottom: auto !important;\n float: right;\n line-height: 1;\n height: calc(var(--message-meta-height, 1rem));\n margin-left: auto;\n margin-right: -0.5rem;\n align-self: flex-end;\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: 0.25rem;\n }\n\n html[data-message-text-size=\"17\"] & {\n top: 0.4375rem;\n }\n\n html[data-message-text-size=\"18\"] &,\n html[data-message-text-size=\"19\"] & {\n top: 0.5rem;\n }\n\n html[data-message-text-size=\"20\"] & {\n top: 0.5625rem;\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: -0.5rem !important;\n margin-top: -0.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 color: var(--color-text);\n background: #cae3f7;\n border-radius: 0.25rem;\n padding: 0 0.125rem;\n\n .theme-dark & {\n --color-text: #000;\n }\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) - 0.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,\n & > .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: 0.25rem;\n }\n\n .via {\n padding-right: 0.25rem;\n font-weight: 400;\n }\n\n span + .via {\n padding-left: 0.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.125rem;\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,\n &.has-background,\n .is-album & {\n background: var(--background-color);\n }\n\n &.has-solid-background {\n padding: 0.3125rem 0.5rem 0.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: -0.0625rem;\n width: 0.5625rem;\n height: 1.125rem;\n font-size: 1rem !important;\n\n .corner {\n fill: var(--background-color);\n }\n\n .Message.own & {\n /* stylelint-disable-next-line plugin/whole-pixel */\n right: -0.551rem; // This value is correct. Safari fix\n }\n\n .Message:not(.own) & {\n /* stylelint-disable-next-line plugin/whole-pixel */\n left: -0.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: 0.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: 0.3125rem;\n }\n }\n\n &.voice,\n &.audio {\n .message-title,\n .Embedded {\n margin-top: -0.1875rem;\n margin-bottom: 0.1875rem;\n }\n }\n\n &.voice {\n padding: 0.5rem !important;\n\n .Voice + .text-content {\n margin-top: 0.5rem;\n }\n }\n\n &.audio {\n min-width: 20rem;\n padding: 0.5rem 0.5rem 0.8125rem !important;\n\n @media (max-width: 600px) {\n min-width: 17rem;\n }\n\n .Audio + .text-content {\n margin-top: 0.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: 0.125rem;\n max-width: calc(100% - 3rem);\n margin-left: calc(100% - 3rem);\n padding: 0 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.message-content.media,\n.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 &:not(.text) .RoundVideo {\n margin-bottom: 0;\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 0.3s ease, transform 0.3s ease;\n }\n }\n\n .icon-large-play,\n .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 0.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, 0.25);\n color: #fff;\n font-size: 0.75rem;\n position: absolute;\n left: 0.1875rem;\n top: 0.1875rem;\n z-index: 1;\n padding: 0 0.375rem;\n border-radius: 0.75rem;\n line-height: 1.125rem;\n user-select: none;\n }\n\n .message-media-duration .icon-muted {\n vertical-align: -0.1875rem;\n margin-left: 0.375rem;\n font-size: 1.0625rem;\n }\n}\n\n.message-content.custom-shape {\n line-height: 1.2;\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)\n 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: 0.5rem;\n min-width: 10rem;\n @media (max-width: 600px) {\n margin-top: 0.375rem;\n }\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.0625rem;\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.0625rem;\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,\n &:active,\n &:visited {\n text-decoration: underline !important;\n }\n}\n\n.text-entity-code,\n.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 cursor: pointer;\n}\n","@import \"message-content\";\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 --color-reaction: var(--color-message-reaction);\n --hover-color-reaction: var(--color-message-reaction-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(\n var(--meta-safe-area-base) + var(--meta-safe-author-width) + var(--meta-safe-area-extra-width)\n );\n --deleting-translate-x: -50%;\n --select-message-scale: 0.9;\n\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 @media (min-width: 1921px) {\n --max-width: calc(30vw - 1rem);\n }\n @media (max-width: 600px) {\n margin-bottom: 0.25rem;\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 margin-right: 0.3125rem;\n\n @media (max-width: 600px) {\n width: 2.5rem;\n height: 2.5rem;\n }\n }\n\n .quick-reaction {\n cursor: pointer;\n position: absolute;\n right: -0.5rem;\n bottom: -0.375rem;\n display: flex;\n align-items: center;\n justify-content: center;\n transform: scale(1);\n opacity: 0;\n transition: transform 0.2s ease-out, opacity 0.2s ease-out;\n transition-delay: 0.2s;\n\n &.visible {\n opacity: 1 !important;\n }\n\n &:hover {\n transition-delay: unset;\n transform: scale(1.4);\n }\n\n .ReactionStaticEmoji {\n width: 1.125rem;\n }\n }\n\n &.last-in-list .quick-reaction:hover {\n transform: translateY(-0.1875rem) scale(1.4);\n }\n\n &.own .quick-reaction {\n right: auto;\n left: -0.5rem;\n }\n\n &.last-in-group {\n margin-bottom: 0.625rem;\n @media (max-width: 600px) {\n margin-bottom: 0.4375rem;\n }\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 &.has-active-reaction {\n .message-content-wrapper {\n z-index: 1;\n }\n }\n\n &:not(.own) {\n padding-left: 2.5rem;\n\n .no-avatars &,\n &.is-thread-top {\n padding-left: 0;\n }\n\n @media (max-width: 600px) {\n padding-left: 2.875rem;\n\n .no-avatars &,\n &.is-thread-top {\n padding-left: 0.25rem;\n }\n }\n\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 flex-direction: row-reverse;\n --background-color: var(--color-background-own);\n --hover-color: var(--color-reply-own-hover);\n --color-reaction: var(--color-message-reaction-own);\n --hover-color-reaction: var(--color-message-reaction-hover-own);\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 &.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 &.is-deleting {\n > .Avatar,\n > .message-content-wrapper {\n transition: opacity 0.2s ease, transform 0.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 .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 position: absolute;\n .Message.own & {\n background: var(--color-background-own);\n }\n\n .message-select-control {\n position: absolute;\n z-index: 2;\n top: 0.4375rem;\n right: 0.4375rem;\n left: unset;\n }\n\n img,\n 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,\n video {\n transform: scale(var(--select-message-scale));\n }\n }\n }\n\n &.is-selected,\n &.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 .message-content.document {\n padding: 0.25rem 0.5rem !important;\n }\n\n &.last-in-document-group {\n .message-content.document {\n padding-bottom: 0.5rem !important;\n }\n }\n\n &.first-in-document-group {\n .message-content.document {\n padding-top: 0.5rem !important;\n }\n }\n\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.6875rem;\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 &.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 .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 .message-content {\n &.has-replies:not(.custom-shape):not(.has-reactions) .WebPage.with-video .media-inner {\n margin-bottom: 1.5rem !important;\n }\n\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: 0.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, 0.2);\n\n opacity: 0;\n transition: opacity 0.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, 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// 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 .custom-shape .message-action-button {\n bottom: 0.25rem;\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: -0.5rem;\n margin-bottom: 0.5rem;\n\n &::before {\n display: none;\n }\n\n &__button.secondary {\n margin-top: 0.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: 0.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: 0.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: 0.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: 0.25rem;\n text-align: center;\n unicode-bidi: plaintext;\n }\n\n .description {\n font-size: 0.9375rem;\n margin: 0;\n padding: 0;\n list-style: none;\n unicode-bidi: plaintext;\n }\n\n .list-checkmarks {\n font-size: 0.9375rem;\n margin: 0.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: 0.5rem;\n }\n }\n}\n","@import \"../../styles/mixins\";\n\n.MessageList {\n flex: 1;\n width: 100%;\n margin-bottom: 0.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 -webkit-touch-callout: none;\n\n &.select-mode-active {\n user-select: auto;\n -webkit-touch-callout: default;\n }\n }\n\n /* stylelint-disable-next-line plugin/no-low-performance-animation-properties */\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 &.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,\n &.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 body:not(.keyboard-visible) & {\n margin-bottom: calc(4.25rem + env(safe-area-inset-bottom));\n }\n }\n }\n }\n\n .Message,\n .ActionMessage {\n position: relative;\n\n opacity: 1;\n transform: scale(1);\n transition: opacity 0.2s ease, transform 0.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: 0.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,\n &: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) - 0.0625rem);\n font-weight: 500;\n line-height: 1.75;\n padding: 0 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) - 0.125rem);\n line-height: calc(var(--message-text-size, 1rem) + 0.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 0.3s ease;\n\n @media (max-width: 600px) {\n margin-top: 0.5rem;\n margin-bottom: 0.75rem;\n }\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: 0.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: max(1rem, env(safe-area-inset-right));\n opacity: 0;\n transform: translateY(4.5rem);\n transition: transform 0.25s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.2s ease;\n z-index: var(--z-scroll-down-button);\n pointer-events: none;\n\n body.animation-level-0 & {\n transform: none !important;\n\n transition: opacity 0.15s;\n }\n\n @media (max-width: 600px) {\n right: 0.5rem;\n bottom: 4.5rem;\n\n body:not(.keyboard-visible) & {\n bottom: calc(4.5rem + env(safe-area-inset-bottom));\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 0.4375rem;\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.3125rem;\n right: -0.3125rem;\n\n background: var(--color-green);\n color: white;\n\n pointer-events: none;\n\n @media (max-width: 600px) {\n top: -0.6875rem;\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",".AttachMenu {\n align-self: flex-end;\n\n &--button {\n &:focus {\n color: var(--color-primary);\n }\n }\n\n &--menu {\n position: relative;\n top: -3.5rem;\n\n @media (max-width: 600px) {\n top: -2.875rem;\n }\n\n .is-pointer-env & {\n > .backdrop {\n position: absolute;\n top: -1rem;\n left: auto;\n right: 0;\n width: 3.5rem;\n }\n }\n\n\n .media-disabled > button {\n white-space: normal;\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: 0.1875rem 0.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: 0.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: 0.375rem;\n }\n }\n}\n",".ComposerEmbeddedMessage {\n height: 2.625rem;\n /* stylelint-disable-next-line plugin/no-low-performance-animation-properties */\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 /* stylelint-disable-next-line plugin/no-low-performance-animation-properties */\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: 0.125rem;\n bottom: 0.0625rem;\n }\n\n &.with-video .media-inner {\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: 0.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: env(safe-area-inset-bottom);\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 /* stylelint-disable-next-line plugin/no-low-performance-animation-properties */\n width: 1rem;\n transform: scale(0);\n }\n\n to {\n /* stylelint-disable-next-line plugin/no-low-performance-animation-properties */\n width: 3.5rem;\n transform: scale(1);\n }\n }\n\n > .Button {\n flex-shrink: 0;\n margin-left: 0.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-schedule,\n .icon-microphone-alt,\n .icon-check {\n position: absolute;\n }\n\n &:not(:active):not(:focus):not(:hover) {\n .icon-send,\n .icon-schedule,\n .icon-check {\n color: var(--color-primary);\n }\n }\n\n &.cancel {\n position: relative;\n z-index: 1;\n\n &:hover,\n &.active {\n background: var(--color-chat-hover);\n }\n }\n\n &.recording {\n position: relative;\n z-index: 0;\n transition: box-shadow 0.1s;\n }\n\n &.send {\n .icon-send {\n animation: grow-icon 0.4s ease-out;\n }\n\n .icon-microphone-alt,\n .icon-check,\n .icon-schedule {\n animation: hide-icon 0.4s forwards ease-out;\n }\n }\n\n &.schedule {\n .icon-schedule {\n animation: grow-icon 0.4s ease-out;\n }\n\n .icon-microphone-alt,\n .icon-check,\n .icon-send {\n animation: hide-icon 0.4s forwards ease-out;\n }\n }\n\n &.record {\n .icon-microphone-alt {\n animation: grow-icon 0.4s ease-out;\n }\n\n .icon-send,\n .icon-check,\n .icon-schedule {\n animation: hide-icon 0.4s forwards ease-out;\n }\n }\n\n &.edit {\n .icon-check {\n animation: grow-icon 0.4s ease-out;\n }\n\n .icon-send,\n .icon-microphone-alt,\n .icon-schedule {\n animation: hide-icon 0.4s forwards ease-out;\n }\n }\n\n &.not-ready > i {\n animation-duration: 0ms !important;\n }\n\n body.animation-level-0 &,\n body.animation-level-1 & {\n .icon-send,\n .icon-microphone-alt,\n .icon-check,\n .icon-schedule {\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 transform-origin: right;\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 0.4s ease-out;\n }\n\n .icon-keyboard,\n .Spinner {\n animation: hide-icon 0.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 0.4s ease-out;\n }\n\n .icon-keyboard,\n .icon-smile {\n animation: hide-icon 0.4s forwards ease-out;\n }\n }\n\n &.menu-opened {\n .icon-keyboard {\n animation: grow-icon 0.4s ease-out;\n }\n\n .icon-smile,\n .Spinner {\n animation: hide-icon 0.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: -0.1875rem;\n /* stylelint-disable-next-line plugin/whole-pixel */\n right: -0.551rem; // This value is correct. Safari fix\n width: 0.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: -0.5rem;\n }\n\n > .AttachMenu > .Button,\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, + .AttachMenu {\n margin-left: -1rem;\n }\n\n @media (max-width: 600px) {\n width: 2.875rem;\n height: 2.875rem;\n\n + .Button, + .AttachMenu {\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: 0.75rem;\n right: 0.875rem;\n border: 0.1875rem solid var(--color-background);\n box-sizing: content-box;\n width: 0.5rem;\n height: 0.5rem;\n border-radius: 50%;\n background: var(--color-green-darker);\n box-shadow: -0.375rem -0.25rem 0 -0.1875rem var(--color-background);\n @media (max-width: 600px) {\n top: 0.5rem;\n right: 0.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: 0.75rem;\n height: 0.75rem;\n background: var(--color-error);\n border-radius: 0.375rem;\n position: absolute;\n top: 50%;\n margin-top: -0.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)\n calc(0.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\",\n sans-serif;\n }\n\n &.overflown {\n overflow-y: auto;\n overflow-x: hidden;\n }\n\n &.touched,\n &: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,\n &:active,\n &:visited {\n text-decoration: underline !important;\n }\n }\n\n .spoiler {\n background-image: url(\"../../../assets/spoiler-dots-black.png\");\n background-size: auto min(100%, 1.125rem);\n border-radius: 0.5rem;\n padding: 0 0.3125rem 0.125rem 0.3125rem;\n text-shadow: -2px -2px 0 var(--color-background), 2px -2px 0 var(--color-background),\n -2px 2px 0 var(--color-background), 2px 2px 0 var(--color-background);\n }\n\n html.theme-dark & .spoiler {\n background-image: url(\"../../../assets/spoiler-dots-white.png\");\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 /* stylelint-disable-next-line plugin/no-low-performance-animation-properties */\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: 0.8125rem;\n left: 0.9375rem;\n }\n}\n\n.composer-tooltip {\n position: absolute;\n bottom: calc(100% + 0.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: 0.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 body:not(.animation-level-0) #root & {\n transition: background-color 0.2s;\n }\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-image 0.2s;\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 .theme-dark #MiddleColumn:not(.custom-bg-image) & {\n background-image: url('../../assets/chat-bg-dark.png');\n background-position: top left;\n background-size: 650px;\n background-repeat: repeat;\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 html.theme-light body.animation-level-2 #Main.right-column-open #MiddleColumn:not(.custom-bg-image) &::after {\n transform: scale(0.67) !important;\n }\n }\n\n html.theme-light 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 .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 &,\n &::before {\n transition: none !important;\n }\n }\n }\n\n .message-input-wrapper,\n &::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,\n color 0.15s;\n\n body.animation-level-0 & {\n transition: none !important;\n }\n }\n\n &.hover-disabled,\n &: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,\n &::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 &-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 .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 /* stylelint-disable-next-line plugin/no-low-performance-animation-properties */\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 &: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 &::before {\n content: \"\";\n position: absolute;\n top: -0.5625rem;\n left: 0;\n right: 0;\n height: 1px;\n background: linear-gradient(\n 90deg,\n rgba(255, 255, 255, 0) 0%,\n rgba(255, 255, 255, 0.4) 2%,\n rgba(255, 255, 255, 0.4) 98%,\n rgba(255, 255, 255, 0) 100%\n );\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(\n 90deg,\n rgba(127, 127, 127, 0) 0%,\n rgba(127, 127, 127, 0.4) 2%,\n rgba(127, 127, 127, 0.4) 98%,\n rgba(127, 127, 127, 0) 100%\n );\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 0.25rem 0.5rem 0.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,\n &: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: 0.75rem;\n color: var(--color-text-secondary);\n font-size: 1.5rem;\n transition: color 0.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 0.15s, color 0.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: calc(0.75rem + env(safe-area-inset-bottom));\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 0.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: 0.875rem 0.5rem 0.5rem;\n box-shadow: inset 0 -0.0625rem 0 0 var(--color-background-secondary-accent);\n border-bottom: 0.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 0.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: 0.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: 0.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 padding-right: env(safe-area-inset-right);\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 @media (max-width: 1275px) {\n box-shadow: 0 0.25rem 0.5rem 0.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 > .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 0.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: 0.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 &,\n 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 transform: translate3d(-20vw, 0, 0);\n left: env(safe-area-inset-left) !important;\n width: calc(100vw - env(safe-area-inset-left)) !important;\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/616.dfb0d60d06da102bbad4.js b/dist/616.421a1d053cdd90ce3d23.js similarity index 99% rename from dist/616.dfb0d60d06da102bbad4.js rename to dist/616.421a1d053cdd90ce3d23.js index 0ee69c44..e7e66276 100644 --- a/dist/616.dfb0d60d06da102bbad4.js +++ b/dist/616.421a1d053cdd90ce3d23.js @@ -1,2 +1,2 @@ "use strict";(self.webpackChunktelegram_t=self.webpackChunktelegram_t||[]).push([[616],{5616:(e,t,n)=>{n.r(t),n.d(t,{Main:()=>So});var a=n(3555),s=n(3716),i=n(4050),o=(n(9005),n(6137)),r=n(5406),c=n(1192),l=n(735),d=n(5806);function u(e){const{chatId:t,threadId:n}=(0,c.Bt)(e)||{};return t&&n?(e=(0,r.qr)(e,t,n,!1),e=(0,r.Pb)(e,t,n,void 0)):e}(0,a.iw)("openLocalTextSearch",(e=>{const{chatId:t,threadId:n}=(0,c.Bt)(e)||{};if(t&&n)return(0,r.qr)(e,t,n,!0)})),(0,a.iw)("closeLocalTextSearch",u),(0,a.iw)("setLocalTextSearchQuery",((e,t,n)=>{const{chatId:a,threadId:s}=(0,c.Bt)(e)||{};if(!a||!s)return;const{query:i}=n,o=(0,d.uw)(a,s),{query:u}=e.localTextSearch.byChatThreadKey[o]||{};return i!==u&&(e=(0,r.Pb)(e,a,s,l.D)),(0,r.qr)(e,a,s,!0,i)})),(0,a.iw)("setLocalMediaSearchType",((e,t,n)=>{const{chatId:a}=(0,c.Bt)(e)||{};if(!a)return;const{mediaType:s}=n;return(0,r.z5)(e,a,s)})),(0,a.iw)("openChat",((e,t,n)=>{const{id:s,threadId:i=o._f,type:l="thread",shouldReplaceHistory:d=!1}=n,m=(0,c.Bt)(e);return m&&m.chatId===s&&m.threadId===i&&m.type===l||(s&&(e=(0,r.pf)(e,s,i,"replyStack",[])),e=u(e=(0,r.i9)(e)),e={...e,isStatisticsShown:!1,messages:{...e.messages,contentToBeScheduled:void 0},...s!==e.forwardMessages.toChatId&&{forwardMessages:{}}},(0,a.R3)(e)),(0,r.Wy)(e,s,i,l,d)})),(0,a.iw)("openPreviousChat",(e=>(0,r.Wy)(e,void 0))),(0,a.iw)("openChatWithInfo",((e,t,n)=>{(0,a.R3)({...e,isChatInfoShown:!0}),t.openChat(n)})),(0,a.iw)("resetChatCreation",(e=>({...e,chatCreation:void 0}))),(0,a.iw)("setNewChatMembersDialogState",((e,t,n)=>({...e,newChatMembersProgress:n}))),(0,a.iw)("openNextChat",((e,t,n)=>{const{targetIndexDelta:a,orderedIds:s}=n,{chatId:i}=(0,c.Bt)(e)||{};if(!i)return void t.openChat({id:s[0]});const o=s.indexOf(i);if(-1===o)return;const r=s[o+a];t.openChat({id:r,shouldReplaceHistory:!0})}));var m=n(1713),h=n(7361),g=n(782),f=n(2267),p=n(257),v=n(3099),I=n(711),y=n(4319);const w=s.ck+s.fK;let Z;function P(e,t,n){const{threadId:a}=(0,c.Bt)(e)||{},s=I.i0,i=(0,c.Zw)(e,t);if(!i||!a)return;const o=n.map((e=>i[e])).filter((t=>(0,c._k)(e,t,a).canCopy)).sort(((e,t)=>e.id-t.id)).reduce(((t,n)=>{const a=(0,c.Ur)(e,n);return t.push(`> ${a?(0,d.OU)(s,a):""}:`),t.push(`${(0,d.MK)(s,n,!1,0,void 0,!0)}\n`),t}),[]);(0,y.TE)(o.join("\n"))}(0,a.iw)("setScrollOffset",((e,t,n)=>{const{chatId:a,threadId:s,scrollOffset:i}=n;return(0,r.pf)(e,a,s,"scrollOffset",i)})),(0,a.iw)("setReplyingToId",((e,t,n)=>{const{messageId:a}=n,s=(0,c.Bt)(e);if(!s)return;const{chatId:i,threadId:o}=s;return(0,r.pf)(e,i,o,"replyingToId",a)})),(0,a.iw)("setEditingId",((e,t,n)=>{const{messageId:a}=n,s=(0,c.Bt)(e);if(!s)return;const{chatId:i,threadId:o,type:l}=s,d="scheduled"===l?"editingScheduledId":"editingId";return(0,r.pf)(e,i,o,d,a)})),(0,a.iw)("setEditingDraft",((e,t,n)=>{const{text:a,chatId:s,threadId:i,type:o}=n,c="scheduled"===o?"editingScheduledDraft":"editingDraft";return(0,r.pf)(e,s,i,c,a)})),(0,a.iw)("editLastMessage",(e=>{const{chatId:t,threadId:n}=(0,c.Bt)(e)||{};if(!t||!n)return;const a=(0,c.Zw)(e,t),s=(0,c.Cb)(e,t,n);if(!a||!s)return;const i=(0,g.dF)(s,(t=>Boolean(a[t]&&(0,c._k)(e,a[t],n).canEdit)));return i?(0,r.pf)(e,t,n,"editingId",i):void 0})),(0,a.iw)("replyToNextMessage",((e,t,n)=>{const{targetIndexDelta:a}=n,{chatId:s,threadId:i}=(0,c.Bt)(e)||{};if(!s||!i)return;const r=(0,c.Zw)(e,s),l=(0,c.Cb)(e,s,i);if(!r||!l)return;const d=(0,c.Yy)(e,s,i);let u;if((0,c.b9)(e,s,i)&&d){const e=Object.keys(r),t=e.indexOf(d.toString())+a;u=t<=e.length+1&&t>=0?Number(e[t]):void 0}else if(i===o._f){var m;const t=(0,c.Z1)(e,s);u=null==t||null===(m=t.lastMessage)||void 0===m?void 0:m.id}else{const t=(0,c.tZ)(e,s,i);u=null==t?void 0:t.lastMessageId}t.setReplyingToId({messageId:u}),t.focusMessage({chatId:s,threadId:i,messageId:u})})),(0,a.iw)("openAudioPlayer",((e,t,n)=>{const{chatId:a,threadId:s,messageId:i,origin:o,volume:r,playbackRate:c,isMuted:l}=n;return{...e,audioPlayer:{chatId:a,threadId:s,messageId:i,origin:null!=o?o:e.audioPlayer.origin,volume:null!=r?r:e.audioPlayer.volume,playbackRate:c||e.audioPlayer.playbackRate,isMuted:l||e.audioPlayer.isMuted}}})),(0,a.iw)("setAudioPlayerVolume",((e,t,n)=>{const{volume:a}=n;return{...e,audioPlayer:{...e.audioPlayer,volume:a}}})),(0,a.iw)("setAudioPlayerPlaybackRate",((e,t,n)=>{const{playbackRate:a}=n;return{...e,audioPlayer:{...e.audioPlayer,playbackRate:a}}})),(0,a.iw)("setAudioPlayerMuted",((e,t,n)=>{const{isMuted:a}=n;return{...e,audioPlayer:{...e.audioPlayer,isMuted:a}}})),(0,a.iw)("setAudioPlayerOrigin",((e,t,n)=>{const{origin:a}=n;return{...e,audioPlayer:{...e.audioPlayer,origin:a}}})),(0,a.iw)("closeAudioPlayer",(e=>({...e,audioPlayer:{volume:e.audioPlayer.volume,playbackRate:e.audioPlayer.playbackRate,isMuted:e.audioPlayer.isMuted}}))),(0,a.iw)("openPollResults",((e,t,n)=>{const{chatId:s,messageId:i}=n;if((0,c.Jf)(e)){if(s!==e.pollResults.chatId||i!==e.pollResults.messageId)return{...e,pollResults:{chatId:s,messageId:i,voters:{}}}}else window.setTimeout((()=>{e=(0,a.Rd)(),(0,a.R3)({...e,pollResults:{chatId:s,messageId:i,voters:{}}})}),450)})),(0,a.iw)("closePollResults",(e=>({...e,pollResults:{}}))),(0,a.iw)("focusLastMessage",((e,t)=>{const n=(0,c.Bt)(e);if(!n)return;const{chatId:a,threadId:s}=n;let i;if(s===o._f){var r;const t=(0,c.Z1)(e,a);i=null==t||null===(r=t.lastMessage)||void 0===r?void 0:r.id}else{const t=(0,c.tZ)(e,a,s);i=null==t?void 0:t.lastMessageId}i&&t.focusMessage({chatId:a,threadId:s,messageId:i,noHighlight:!0})})),(0,a.iw)("focusNextReply",((e,t)=>{const n=(0,c.Bt)(e);if(!n)return;const{chatId:s,threadId:i}=n,o=(0,c.p9)(e,s,i);if(o&&0!==o.length){const n=o.pop();e=(0,r.pf)(e,s,i,"replyStack",[...o]),(0,a.R3)(e),t.focusMessage({chatId:s,threadId:i,messageId:n})}else t.focusLastMessage()})),(0,a.iw)("focusMessage",((e,t,n)=>{const{chatId:s,threadId:i=o._f,messageListType:l="thread",noHighlight:d,groupedId:u,groupedChatId:h,replyMessageId:g,isResizingContainer:f}=n;let{messageId:p}=n;if(void 0!==u){const t=(0,c.y8)(e,h,u);null!=t&&t.length&&([p]=t)}const v=(0,c.Bt)(e),I=!v||s!==v.chatId||i!==v.threadId||l!==v.type;if(Z&&(clearTimeout(Z),Z=void 0),Z=window.setTimeout((()=>{let e=(0,a.Rd)();e=(0,r.cq)(e),e=(0,r.wV)(e),(0,a.R3)(e)}),d?w:1500),e=(0,r.cq)(e,s,p,d,f),e=(0,r.wV)(e,void 0),g){const t=(0,c.p9)(e,s,i)||[];e=(0,r.pf)(e,s,i,"replyStack",[...t,g])}I&&(e=(0,r.wV)(e,m.fo.Static));const y=(0,c.Cb)(e,s,i);if(y&&y.includes(p))return(0,a.R3)(e),void t.openChat({id:s,threadId:i});if(I&&(e=(0,r.pf)(e,s,i,"viewportIds",void 0)),e=(0,r.pf)(e,s,i,"outlyingIds",void 0),y&&!I){const t=p>y[0]?m.fo.Down:m.fo.Up;e=(0,r.wV)(e,t)}(0,a.R3)(e),t.openChat({id:s,threadId:i}),t.loadViewportMessages()})),(0,a.iw)("openForwardMenu",((e,t,n)=>{const{fromChatId:a,messageIds:s,groupedId:i}=n;let o;return i&&(o=(0,c.xH)(e,a,i)),{...e,forwardMessages:{fromChatId:a,messageIds:o||s,isModalShown:!0}}})),(0,a.iw)("exitForwardMode",(e=>{(0,a.R3)({...e,forwardMessages:{}})})),(0,a.iw)("setForwardChatId",((e,t,n)=>{const{id:s}=n;(0,a.R3)({...e,forwardMessages:{...e.forwardMessages,toChatId:s,isModalShown:!1}}),t.openChat({id:s}),t.closeMediaViewer(),t.exitMessageSelectMode()})),(0,a.iw)("openForwardMenuForSelectedMessages",((e,t)=>{if(!e.selectedMessages)return;const{chatId:n,messageIds:a}=e.selectedMessages;t.openForwardMenu({fromChatId:n,messageIds:a})})),(0,a.iw)("cancelMessageMediaDownload",((e,t,n)=>{const{message:s}=n,i=e.activeDownloads.byChatId[s.chatId];i&&i.length&&(0,a.R3)({...e,activeDownloads:{byChatId:{...e.activeDownloads.byChatId,[s.chatId]:i.filter((e=>e!==s.id))}}})})),(0,a.iw)("downloadMessageMedia",((e,t,n)=>{const{message:s}=n;s&&(0,a.R3)({...e,activeDownloads:{byChatId:{...e.activeDownloads.byChatId,[s.chatId]:[...e.activeDownloads.byChatId[s.chatId]||[],s.id]}}})})),(0,a.iw)("downloadSelectedMessages",((e,t)=>{if(!e.selectedMessages)return;const{chatId:n,messageIds:a}=e.selectedMessages,{threadId:s}=(0,c.Bt)(e)||{},i=(0,c.Zw)(e,n);i&&s&&a.map((e=>i[e])).filter((t=>(0,c._k)(e,t,s).canDownload)).forEach((e=>t.downloadMessageMedia({message:e})))})),(0,a.iw)("enterMessageSelectMode",((e,t,n)=>{const{messageId:a}=n||{},s=(0,c.jr)(e);return s?(0,r.M6)(e,s.id,a):e})),(0,a.iw)("toggleMessageSelection",((e,t,n)=>{const{messageId:s,groupedId:i,childMessageIds:o,withShift:l}=n,d=(0,c.Bt)(e);if(!d)return;const{chatId:u,threadId:m,type:g}=d;e=(0,r.Ob)(e,u,m,g,s,i,o,l),(0,a.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,a.iw)("disableContextMenuHint",(e=>{if(e.shouldShowContextMenuHint)return{...e,shouldShowContextMenuHint:!1}})),(0,a.iw)("exitMessageSelectMode",r.i9),(0,a.iw)("openPollModal",(e=>({...e,isPollModalOpen:!0}))),(0,a.iw)("closePollModal",(e=>({...e,isPollModalOpen:!1}))),(0,a.iw)("checkVersionNotification",((e,t)=>{const n=s.Ji.split(".").slice(0,2).join("."),{serviceNotifications:a}=e;if(a.find((e=>{let{version:t}=e;return t===n})))return;const i={chatId:s.aw,date:(0,f.b)(e.serverTimeOffset),content:{text:(0,v.Z)(p)},isOutgoing:!1};t.createServiceNotification({message:i,version:n})})),(0,a.iw)("createServiceNotification",((e,t,n)=>{var i;const{message:o,version:r}=n,{serviceNotifications:l}=e,d=(0,c.Z1)(e,s.aw),u=Math.max((null===(i=d.lastMessage)||void 0===i?void 0:i.id)||0,...l.map((e=>{let{id:t}=e;return t}))),m=(l.length+1)/1e3,h=Math.floor(u)+m;o.id=h;const g={id:h,message:o,version:r,isUnread:!0};(0,a.R3)({...e,serviceNotifications:[...l.slice(-1e3),g]}),t.apiUpdate({"@type":"newMessage",id:o.id,chatId:o.chatId,message:o})})),(0,a.iw)("openReactorListModal",((e,t,n)=>{const{chatId:a,messageId:s}=n;return{...e,reactorModal:{chatId:a,messageId:s}}})),(0,a.iw)("closeReactorListModal",(e=>({...e,reactorModal:void 0}))),(0,a.iw)("openSeenByModal",((e,t,n)=>{const{chatId:a,messageId:s}=n;return{...e,seenByModal:{chatId:a,messageId:s}}})),(0,a.iw)("closeSeenByModal",(e=>({...e,seenByModal:void 0}))),(0,a.iw)("copySelectedMessages",(e=>{if(!e.selectedMessages)return;const{chatId:t,messageIds:n}=e.selectedMessages;P(e,t,n)})),(0,a.iw)("copyMessagesByIds",((e,t,n)=>{const{messageIds:a}=n,s=(0,c.jr)(e);a&&0!==a.length&&s&&P(e,s.id,a)})),(0,a.iw)("setGlobalSearchQuery",((e,t,n)=>{const{query:a}=n,{chatId:s}=e.globalSearch;return(0,r.No)(e,{globalResults:{},localResults:{},resultsByType:void 0,...a?{fetchingStatus:{chats:!s,messages:!0}}:{fetchingStatus:void 0},query:a})})),(0,a.iw)("addRecentlyFoundChatId",((e,t,n)=>{const{id:a}=n,{recentlyFoundChatIds:s}=e.globalSearch;if(!s)return(0,r.No)(e,{recentlyFoundChatIds:[a]});const i=s.filter((e=>e!==a));return i.unshift(a),i.length>10&&i.pop(),(0,r.No)(e,{recentlyFoundChatIds:i})})),(0,a.iw)("clearRecentlyFoundChats",(e=>(0,r.No)(e,{recentlyFoundChatIds:void 0}))),(0,a.iw)("setGlobalSearchContent",((e,t,n)=>{const{content:a}=n;return(0,r.Og)(e,a)})),(0,a.iw)("setGlobalSearchChatId",((e,t,n)=>{const{id:a}=n;return(0,r.No)(e,{chatId:a,query:void 0,resultsByType:void 0})})),(0,a.iw)("setStickerSearchQuery",((e,t,n)=>{const{query:a}=n;return{...e,stickers:{...e.stickers,search:{query:a,resultIds:void 0}}}})),(0,a.iw)("setGifSearchQuery",((e,t,n)=>{const{query:a}=n;return{...e,gifs:{...e.gifs,search:{query:a,offsetId:void 0,results:void 0}}}})),(0,a.iw)("setUserSearchQuery",((e,t,n)=>{const{query:a}=n;return(0,r.Lm)(e,{globalUserIds:void 0,localUserIds:void 0,fetchingStatus:Boolean(a),query:a})})),(0,a.iw)("openAddContactDialog",((e,t,n)=>{const{userId:a}=n;return{...e,newContact:{userId:a}}})),(0,a.iw)("openNewContactDialog",(e=>({...e,newContact:{isByPhoneNumber:!0}}))),(0,a.iw)("closeNewContactDialog",(e=>(0,r.ft)(e))),n(3456);var C=n(1947),b=n(6926);(0,a.iw)("toggleChatInfo",((e,t,n)=>({...e,isChatInfoShown:void 0!==n?n:!e.isChatInfoShown}))),(0,a.iw)("setLeftColumnWidth",((e,t,n)=>({...e,leftColumnWidth:n}))),(0,a.iw)("resetLeftColumnWidth",(e=>({...e,leftColumnWidth:void 0}))),(0,a.iw)("toggleManagement",(e=>{const{chatId:t}=(0,c.Bt)(e)||{};if(t)return{...e,management:{byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t],isActive:!(e.management.byChatId[t]||{}).isActive}}}}})),(0,a.iw)("requestNextManagementScreen",((e,t,n)=>{const{screen:a}=n||{},{chatId:s}=(0,c.Bt)(e)||{};if(s)return{...e,management:{byChatId:{...e.management.byChatId,[s]:{...e.management.byChatId[s],isActive:!0,nextScreen:a}}}}})),(0,a.iw)("closeManagement",(e=>{const{chatId:t}=(0,c.Bt)(e)||{};if(t)return{...e,management:{byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t],isActive:!1}}}}})),(0,a.iw)("openChat",(e=>{if(h.wB||h.p7)return{...e,isLeftColumnShown:0===e.messages.messageLists.length}})),(0,a.iw)("toggleStatistics",(e=>({...e,isStatisticsShown:!e.isStatisticsShown}))),(0,a.iw)("toggleLeftColumn",(e=>({...e,isLeftColumnShown:!e.isLeftColumnShown}))),(0,a.iw)("addRecentEmoji",((e,t,n)=>{const{emoji:a}=n,{recentEmojis:s}=e;if(!s)return{...e,recentEmojis:[a]};const i=s.filter((e=>e!==a));return i.unshift(a),i.length>18&&i.pop(),{...e,recentEmojis:i}})),(0,a.iw)("addRecentSticker",((e,t,n)=>{const{sticker:a}=n,{recent:s}=e.stickers;if(!s)return{...e,stickers:{...e.stickers,recent:{hash:"0",stickers:[a]}}};const i=s.stickers.filter((e=>e.id!==a.id));return i.unshift(a),{...e,stickers:{...e.stickers,recent:{...s,stickers:i}}}})),(0,a.iw)("showNotification",((e,t,n)=>{const a=n;a.localId=(0,b.Z)({});const s=[...e.notifications],i=s.findIndex((e=>e.message===a.message));return-1!==i&&s.splice(i,1),s.push(a),{...e,notifications:s}})),(0,a.iw)("dismissNotification",((e,t,n)=>{const a=e.notifications.filter((e=>{let{localId:t}=e;return t!==n.localId}));return{...e,notifications:a}})),(0,a.iw)("showDialog",((e,t,n)=>{const{data:a}=n;if("message"in a&&a.hasErrorKey&&!(0,C.ZP)(a))return e;const s=[...e.dialogs];if("message"in a){const e=s.findIndex((e=>e.message===a.message));-1!==e&&s.splice(e,1)}return s.push(a),{...e,dialogs:s}})),(0,a.iw)("dismissDialog",(e=>{const t=[...e.dialogs];return t.pop(),{...e,dialogs:t}})),(0,a.iw)("toggleSafeLinkModal",((e,t,n)=>{const{url:a}=n;return{...e,safeLinkModalUrl:a}})),(0,a.iw)("openHistoryCalendar",((e,t,n)=>{const{selectedAt:a}=n;return{...e,historyCalendarSelectedAt:a}})),(0,a.iw)("closeHistoryCalendar",(e=>({...e,historyCalendarSelectedAt:void 0}))),(0,a.iw)("openPaymentModal",((e,t,n)=>{const{chatId:a,messageId:s}=n;return{...e,payment:{...e.payment,chatId:a,messageId:s,isPaymentModalOpen:!0}}})),(0,a.iw)("closePaymentModal",(e=>(e=(0,r.bp)(e),(0,r.WY)(e)))),(0,a.iw)("addPaymentError",((e,t,n)=>{const{error:a}=n;return{...e,payment:{...e.payment,error:a}}})),n(8422),(0,a.iw)("openMediaViewer",((e,t,n)=>{const{chatId:a,threadId:s,messageId:i,avatarOwnerId:o,profilePhotoIndex:r,origin:c,volume:l,playbackRate:d,isMuted:u}=n;return{...e,mediaViewer:{...e.mediaViewer,chatId:a,threadId:s,messageId:i,avatarOwnerId:o,profilePhotoIndex:r,origin:c,volume:null!=l?l:e.mediaViewer.volume,playbackRate:d||e.mediaViewer.playbackRate,isMuted:u||e.mediaViewer.isMuted},forwardMessages:{}}})),(0,a.iw)("closeMediaViewer",(e=>{const{volume:t,isMuted:n,playbackRate:a}=e.mediaViewer;return{...e,mediaViewer:{volume:t,isMuted:n,playbackRate:a}}})),(0,a.iw)("setMediaViewerVolume",((e,t,n)=>{const{volume:a}=n;return{...e,mediaViewer:{...e.mediaViewer,volume:a}}})),(0,a.iw)("setMediaViewerPlaybackRate",((e,t,n)=>{const{playbackRate:a}=n;return{...e,mediaViewer:{...e.mediaViewer,playbackRate:a}}})),(0,a.iw)("setMediaViewerMuted",((e,t,n)=>{const{isMuted:a}=n;return{...e,mediaViewer:{...e.mediaViewer,isMuted:a}}})),n(5456),n(7225);var S=n(1226),E=n(9118);const M=new Map,k=(0,E.Ds)((e=>e()),500,!1);async function R(e,t,n,i){let o=arguments.length>4&&void 0!==arguments[4]&&arguments[4],l=arguments.length>5&&void 0!==arguments[5]&&arguments[5];const d=e.id;let u;switch(i){case m.Uq.Backwards:u=void 0;break;case m.Uq.Around:u=-(Math.round(s.hT/2)+1);break;case m.Uq.Forwards:u=-(s.hT+1)}const h=await(0,S.t9)("fetchMessages",{chat:(0,c.Cm)((0,a.Rd)(),d,t),offsetId:n,addOffset:u,limit:s.hT,threadId:t});if(!h)return;const{messages:f,users:p,chats:v,threadInfos:I}=h;let y=(0,a.Rd)();const w=d===s.aw?y.serviceNotifications.map((e=>{let{message:t}=e;return t})):[],Z=[].concat(f,w),P=(0,g.ee)(Z,"id"),C=Object.keys(P).map(Number);y=(0,r.c_)(y,d,P),y=o?(0,r.ff)(y,d,t,C):(0,r.xj)(y,d,t,C),y=(0,r.Sh)(y,(0,g.ee)(p,"id")),y=(0,r.fZ)(y,(0,g.ee)(v,"id")),y=(0,r.j6)(y,d,I);let b=(0,c.gb)(y,d,t);const E=(0,c.qC)(y,d,t);if(o&&b&&E&&(E.length&&!(0,g.YE)(b,E)||(y=(0,r.xj)(y,d,t,E),b=(0,c.gb)(y,d,t),y=(0,r.pf)(y,d,t,"outlyingIds",void 0),o=!1)),!l){const e=o?E:b,{newViewportIds:a}=N(e,n,i);y=(0,r.y9)(y,d,t,a)}(0,a.R3)(y)}function N(e,t,n){const{length:a}=e,i=t?function(e,t){return te[e.length-1]?e.length-1:e.findIndex(((n,a)=>n===t||nt))}(e,t):-1,o=n===m.Uq.Backwards?i:i+1||a,r=o-s.hT,c=o+s.hT-1,l=e.slice(Math.max(0,r),c+1);let d,u;switch(n){case m.Uq.Backwards:d=o>0,u=r>=0;break;case m.Uq.Forwards:d=o0,u=l.length===s.hT}return{newViewportIds:l,areSomeLocal:d,areAllLocal:u}}async function T(e){let t;const n=e.attachment?(e,s)=>{M.has(s)||(t=s,M.set(s,n));const i=(0,a.Rd)();(0,a.R3)({...i,fileUploads:{byMessageLocalId:{...i.fileUploads.byMessageLocalId,[s]:{progress:e}}}})}:void 0;(e.replyingTo||h.cj)&&await(0,E.Pn)();const s=(0,a.Rd)();e.serverTimeOffset=s.serverTimeOffset;const i=(0,c.Bt)(s);if(!i)return;const{threadId:r}=i;e.replyingTo||r===o._f||(e.replyingTo=(0,c.qS)(s,e.chat.id,r)),await(0,S.t9)("sendMessage",e,n),n&&t&&M.delete(t)}(0,a.iw)("loadViewportMessages",((e,t,n)=>{const{direction:a=m.Uq.Around,isBudgetPreload:i=!1}=n||{};let{chatId:o,threadId:l}=n||{};if(!o){const t=(0,c.Bt)(e);if(!t)return;o=t.chatId,l=t.threadId}const d=(0,c.Z1)(e,o);if(!d||d.isRestricted)return;const u=(0,c.Cb)(e,o,l),h=(0,c.gb)(e,o,l),g=(0,c.qC)(e,o,l);if(u&&u.length&&a!==m.Uq.Around){const n=a===m.Uq.Backwards?u[0]:u[u.length-1],s=Boolean(g),c=s?g:h,{newViewportIds:f,areSomeLocal:p,areAllLocal:v}=N(c,n,a);if(p&&(e=(0,r.y9)(e,o,l,f)),async function(e,t,n,a,s,i,o,r){t||await R(s,i,r,o,n,a),a||(await Promise.resolve(),e.loadViewportMessages({chatId:s.id,threadId:i,direction:o,isBudgetPreload:!0}))}(t,v,s,i,d,l,a,n),i)return}else{const t=(0,c.G$)(e,o)||(0,c.rd)(e,o,l),n=Boolean(t&&h&&!h.includes(t)),a=(n?g:h)||[],{newViewportIds:u,areSomeLocal:f,areAllLocal:p}=N(a,t,m.Uq.Around);f&&u.length>=s.hT&&(e=(0,r.y9)(e,o,l,u)),p||R(d,l,t,m.Uq.Around,n,i)}return e})),(0,a.iw)("loadMessage",(async(e,t,n)=>{const{chatId:s,messageId:i,replyOriginForId:l,threadUpdate:d}=n,u=(0,c.Z1)(e,s);if(!u)return;const m=await async function(e,t,n){const s=await(0,S.t9)("fetchMessage",{chat:e,messageId:t});if(!s)return;if(s===o._Q){if(n){let t=(0,a.Rd)();const s=(0,c.hj)(t,e.id,n);t=(0,r.cY)(t,e.id,n,{...s,replyToMessageId:void 0}),(0,a.R3)(t)}return}let i=(0,a.Rd)();return i=(0,r.cY)(i,e.id,t,s.message),i=(0,r.Sh)(i,(0,g.ee)(s.users,"id")),(0,a.R3)(i),s.message}(u,i,l);if(m&&d){const{lastMessageId:e,isDeleting:t}=d;return(0,r.lG)((0,a.Rd)(),m,s,e,t)}})),(0,a.iw)("sendMessage",((e,t,n)=>{const a=(0,c.Bt)(e);if(!a)return;const{chatId:i,threadId:o,type:r}=a;if("scheduled"===r&&!n.scheduledAt)return{...e,messages:{...e.messages,contentToBeScheduled:n}};const l=(0,c.Z1)(e,i),d={...n,chat:l,replyingTo:(0,c.Yy)(e,i,o),noWebPage:(0,c.tV)(e,i,o),sendAs:(0,c._5)(e,i)};t.setReplyingToId({messageId:void 0}),t.clearWebPagePreview({chatId:i,threadId:o,value:!1});const u=!n.attachments||n.attachments.length<=1,m=!u&&n.attachments&&n.attachments.length>1;if(u){const{attachments:e,...t}=d;T({...t,attachment:e?e[0]:void 0})}else if(m){const{text:e,entities:t,attachments:n,...a}=d,i=(0,g.Vl)(n,s.DU);for(let n=0;n0?r:void 0}),o.forEach((e=>{T({...a,attachment:e,groupedId:r})}))}}else{const{text:e,entities:t,attachments:n,replyingTo:a,...s}=d;e&&T({...s,text:e,entities:t,replyingTo:a}),n.forEach((e=>{T({...s,attachment:e})}))}})),(0,a.iw)("editMessage",((e,t,n)=>{const{serverTimeOffset:a}=e,{text:s,entities:i}=n,o=(0,c.Bt)(e);if(!o)return;const{chatId:r,threadId:l,type:d}=o,u=(0,c.Z1)(e,r),m=(0,c.kK)(e,r,l,d);u&&m&&((0,S.t9)("editMessage",{chat:u,message:m,text:s,entities:i,noWebPage:(0,c.tV)(e,r,l),serverTimeOffset:a}),t.setEditingId({messageId:void 0}))})),(0,a.iw)("cancelSendingMessage",((e,t,n)=>{const{chatId:a,messageId:s}=n,i=(0,c.hj)(e,a,s),o=i&&M.get(i.previousLocalId||i.id);o&&(0,S.u3)(o),t.apiUpdate({"@type":"deleteMessages",ids:[s],chatId:a})})),(0,a.iw)("saveDraft",((e,t,n)=>{const{chatId:a,threadId:s,draft:i}=n;if(!i)return;const{text:l,entities:d}=i,u=(0,c.Z1)(e,a);return s===o._f&&(0,S.t9)("saveDraft",{chat:u,text:l,entities:d,replyToMsgId:(0,c.Yy)(e,a,s)}),e=(0,r.pf)(e,a,s,"draft",i),(0,r.a4)(e,a,{draftDate:Math.round(Date.now()/1e3)})})),(0,a.iw)("clearDraft",((e,t,n)=>{const{chatId:a,threadId:s,localOnly:i}=n;if(!(0,c.Ms)(e,a,s))return;const l=(0,c.Z1)(e,a);return i||s!==o._f||(0,S.t9)("clearDraft",l),e=(0,r.pf)(e,a,s,"draft",void 0),(0,r.a4)(e,a,{draftDate:void 0})})),(0,a.iw)("toggleMessageWebPage",((e,t,n)=>{const{chatId:a,threadId:s,noWebPage:i}=n;return(0,r.pf)(e,a,s,"noWebPage",i)})),(0,a.iw)("pinMessage",((e,t,n)=>{const a=(0,c.jr)(e);if(!a)return;const{messageId:s,isUnpin:i,isOneSide:o,isSilent:r}=n;(0,S.t9)("pinMessage",{chat:a,messageId:s,isUnpin:i,isOneSide:o,isSilent:r})})),(0,a.iw)("unpinAllMessages",((e,t,n)=>{const s=(0,c.Z1)(e,n.chatId);s&&async function(e){await(0,S.t9)("unpinAllMessages",{chat:e});let t=(0,a.Rd)();t=(0,r.pf)(t,e.id,o._f,"pinnedIds",[]),(0,a.R3)(t)}(s)})),(0,a.iw)("deleteMessages",((e,t,n)=>{const{messageIds:a,shouldDeleteForAll:s}=n,i=(0,c.Bt)(e);if(!i)return;const{chatId:o,threadId:r}=i,l=(0,c.Z1)(e,o);(0,S.t9)("deleteMessages",{chat:l,messageIds:a,shouldDeleteForAll:s});const d=(0,c._$)(e,o,r);a.includes(d)&&t.setEditingId({messageId:void 0})})),(0,a.iw)("deleteScheduledMessages",((e,t,n)=>{const{messageIds:a}=n,s=(0,c.Bt)(e);if(!s)return;const{chatId:i}=s,o=(0,c.Z1)(e,i);(0,S.t9)("deleteScheduledMessages",{chat:o,messageIds:a});const r=(0,c.wU)(e,i);a.includes(r)&&t.setEditingId({messageId:void 0})})),(0,a.iw)("deleteHistory",(async(e,t,n)=>{var a;const{chatId:s,shouldDeleteForAll:i}=n,o=(0,c.Z1)(e,s);if(!o)return;const r=null===(a=o.lastMessage)||void 0===a?void 0:a.id;await(0,S.t9)("deleteHistory",{chat:o,shouldDeleteForAll:i,maxId:r});const l=(0,c.Bt)(e);l&&l.chatId===s&&t.openChat({id:void 0})})),(0,a.iw)("reportMessages",(async(e,t,n)=>{const{messageIds:a,reason:s,description:i}=n,o=(0,c.Bt)(e);if(!o)return;const{chatId:r}=o,l=(0,c.Z1)(e,r),d=await(0,S.t9)("reportMessages",{peer:l,messageIds:a,reason:s,description:i});t.showNotification({message:d?"Thank you! Your report will be reviewed by our team.":"Error occured while submiting report. Please, try again later."})})),(0,a.iw)("sendMessageAction",(async(e,t,n)=>{const{action:a,chatId:s,threadId:i}=n;if(s===e.currentUserId)return;const o=(0,c.Z1)(e,s);o&&await(0,S.t9)("sendMessageAction",{peer:o,threadId:i,action:a})})),(0,a.iw)("markMessageListRead",((e,t,n)=>{const{serverTimeOffset:a}=e,i=(0,c.Bt)(e);if(!i)return;const{chatId:l,threadId:d}=i,u=(0,c.Cm)(e,l,d);if(!u)return;const{maxId:m}=n;if(k((()=>{(0,S.t9)("markMessageListRead",{serverTimeOffset:a,chat:u,threadId:d,maxId:m})})),d!==o._f)return;l===s.aw&&(e={...e,serviceNotifications:e.serviceNotifications.map((e=>e.isUnread&&e.id<=m?{...e,isUnread:!1}:e))});const h=(0,c.Cb)(e,l,d),g=(0,c.It)(e,l,d);if(!h||!g||!u.unreadCount)return e;const f=function(e,t,n){let a=0;for(let s=0,i=e.length;s=t&&e[s]<=n&&a++,!(e[s]>=n));s++);return a}(h,g,m);return f?(0,r.a4)(e,l,{lastReadInboxMessageId:m,unreadCount:Math.max(0,u.unreadCount-f)}):e})),(0,a.iw)("markMessagesRead",((e,t,n)=>{const a=(0,c.jr)(e);if(!a)return;const{messageIds:s}=n;(0,S.t9)("markMessagesRead",{chat:a,messageIds:s})})),(0,a.iw)("loadWebPagePreview",((e,t,n)=>{const{text:s}=n;!async function(e){const t=await(0,S.t9)("fetchWebPagePreview",{message:e});(0,a.R3)({...(0,a.Rd)(),webPagePreview:t})}(s)})),(0,a.iw)("clearWebPagePreview",(e=>{if(e.webPagePreview)return{...e,webPagePreview:void 0}})),(0,a.iw)("sendPollVote",((e,t,n)=>{const{chatId:a,messageId:s,options:i}=n,o=(0,c.Z1)(e,a);o&&(0,S.t9)("sendPollVote",{chat:o,messageId:s,options:i})})),(0,a.iw)("loadPollOptionResults",((e,t,n)=>{const{chat:s,messageId:i,option:o,offset:c,limit:l,shouldResetVoters:d}=n;!async function(e,t,n,s,i,o){const c=await(0,S.t9)("loadPollOptionResults",{chat:e,messageId:t,option:n,offset:s,limit:i});if(!c)return;let l=(0,a.Rd)();l=(0,r.Sh)(l,(0,g.ee)(c.users,"id"));const{voters:d}=l.pollResults;(0,a.R3)({...l,pollResults:{...l.pollResults,voters:{...d,[n]:(0,g.Tw)([...!o&&d&&d[n]?d[n]:[],...c&&c.users.map((e=>e.id))])},offsets:{...l.pollResults.offsets?l.pollResults.offsets:{},[n]:c.nextOffset||""}}})}(s,i,o,c,l,d)})),(0,a.iw)("forwardMessages",((e,t,n)=>{const{fromChatId:s,messageIds:i,toChatId:o}=e.forwardMessages,r=s?(0,c.Z1)(e,s):void 0,l=o?(0,c.Z1)(e,o):void 0,u=s&&i?i.sort(((e,t)=>e-t)).map((t=>(0,c.hj)(e,s,t))).filter(Boolean):void 0;if(!r||!l||!u)return;const{isSilent:m,scheduledAt:h}=n,g=(0,c._5)(e,o),f=u.filter((e=>!(0,d.jM)(e)));f.length&&(0,S.t9)("forwardMessages",{fromChat:r,toChat:l,messages:f,serverTimeOffset:(0,a.Rd)().serverTimeOffset,isSilent:m,scheduledAt:h,sendAs:g}),u.filter((e=>(0,d.jM)(e))).forEach((e=>{const{text:t,entities:n}=e.content.text||{},{sticker:a,poll:s}=e.content;T({chat:l,text:t,entities:n,sticker:a,poll:s,isSilent:m,scheduledAt:h,sendAs:g})})),(0,a.R3)({...(0,a.Rd)(),forwardMessages:{}})})),(0,a.iw)("loadScheduledHistory",((e,t,n)=>{const{chatId:s}=n,i=(0,c.Z1)(e,s);i&&async function(e){const t=await(0,S.t9)("fetchScheduledHistory",{chat:e});if(!t)return;const{messages:n}=t,s=(0,g.ee)(n,"id"),i=Object.keys(s).map(Number).sort(((e,t)=>t-e));let c=(0,a.Rd)();c=(0,r.w3)(c,e.id,s),c=(0,r.pf)(c,e.id,o._f,"scheduledIds",i),(0,a.R3)(c)}(i)})),(0,a.iw)("sendScheduledMessages",((e,t,n)=>{const{chatId:a,id:s}=n,i=(0,c.Z1)(e,a);i&&(0,S.t9)("sendScheduledMessages",{chat:i,ids:[s]})})),(0,a.iw)("rescheduleMessage",((e,t,n)=>{const{chatId:a,messageId:s,scheduledAt:i}=n,o=(0,c.Z1)(e,a),r=o&&(0,c.Tm)(e,o.id,s);o&&r&&(0,S.t9)("rescheduleMessage",{chat:o,message:r,scheduledAt:i})})),(0,a.iw)("requestThreadInfoUpdate",((e,t,n)=>{const{chatId:a,threadId:s}=n,i=(0,c.Cm)(e,a,s);i&&(0,S.t9)("requestThreadInfoUpdate",{chat:i,threadId:s})})),(0,a.iw)("loadPinnedMessages",((e,t,n)=>{const{chatId:s}=n,i=(0,c.Z1)(e,s);i&&async function(e){const t=await(0,S.t9)("fetchPinnedMessages",{chat:e});if(!t)return;const{messages:n,chats:s,users:i}=t,c=(0,g.ee)(n,"id"),l=Object.keys(c).map(Number).sort(((e,t)=>t-e));let d=(0,a.Rd)();d=(0,r.c_)(d,e.id,c),d=(0,r.pf)(d,e.id,o._f,"pinnedIds",l),d=(0,r.Sh)(d,(0,g.ee)(i,"id")),d=(0,r.fZ)(d,(0,g.ee)(s,"id")),(0,a.R3)(d)}(i)})),(0,a.iw)("loadSeenBy",(async(e,t,n)=>{const{chatId:s,messageId:i}=n,o=(0,c.Z1)(e,s);if(!o)return;const l=await(0,S.t9)("fetchSeenBy",{chat:o,messageId:i});return l?(0,r.cY)((0,a.Rd)(),s,i,{seenByUserIds:l}):void 0})),(0,a.iw)("saveDefaultSendAs",((e,t,n)=>{const{chatId:a,sendAsId:s}=n,i=(0,c.Z1)(e,a),o=(0,c.Z1)(e,s)||(0,c.dy)(e,s);if(i&&o)return(0,S.t9)("saveDefaultSendAs",{sendAs:o,chat:i}),(0,r.a4)(e,a,{fullInfo:{...i.fullInfo,sendAsId:s}})})),(0,a.iw)("loadSendAs",(async(e,t,n)=>{const{chatId:s}=n,i=(0,c.Z1)(e,s);if(!i)return;const o=await(0,S.t9)("fetchSendAs",{chat:i});return o?(e=(0,a.Rd)(),e=(0,r.Sh)(e,(0,g.ee)(o.users,"id")),e=(0,r.fZ)(e,(0,g.ee)(o.chats,"id")),e=(0,r.a4)(e,s,{sendAsIds:o.ids})):(0,r.a4)((0,a.Rd)(),s,{sendAsIds:[]})})),(0,a.iw)("loadSponsoredMessages",(async(e,t,n)=>{const{chatId:s}=n,i=(0,c.Z1)(e,s);if(!i)return;const o=await(0,S.t9)("fetchSponsoredMessages",{chat:i});return o?(e=(0,a.Rd)(),e=(0,r.Fn)(e,s,o.messages[0]),e=(0,r.Sh)(e,(0,g.ee)(o.users,"id")),e=(0,r.fZ)(e,(0,g.ee)(o.chats,"id"))):void 0})),(0,a.iw)("viewSponsoredMessage",((e,t,n)=>{const{chatId:a}=n,s=(0,c.Z1)(e,a),i=(0,c.fS)(e,a);s&&i&&(0,S.t9)("viewSponsoredMessage",{chat:s,random:i.randomId})}));var B=n(5765);const A=(0,E.P2)((e=>e()),500,!1);async function x(e,t){const n=await(0,S.t9)("searchGifs",{query:e,offset:t});n&&(0,a.R3)((0,r.rq)((0,a.Rd)(),!t,n.gifs,n.nextOffset))}(0,a.iw)("loadStickerSets",(e=>{const{hash:t}=e.stickers.added||{};!async function(e){const t=await(0,S.t9)("fetchStickerSets",{hash:e});t&&(0,a.R3)((0,r.z3)((0,a.Rd)(),"added",t.hash,t.sets))}(t)})),(0,a.iw)("loadAddedStickers",(async(e,t)=>{const{setIds:n}=e.stickers.added,a=e.stickers.setsById;if(n&&n.length)for(let e=0;e0&&await(0,E.wO)(200))}})),(0,a.iw)("loadRecentStickers",(e=>{const{hash:t}=e.stickers.recent||{};!async function(e){const t=await(0,S.t9)("fetchRecentStickers",{hash:e});if(!t)return;const n=(0,a.Rd)();(0,a.R3)({...n,stickers:{...n.stickers,recent:t}})}(t)})),(0,a.iw)("loadFavoriteStickers",(e=>{const{hash:t}=e.stickers.favorite||{};!async function(e){const t=await(0,S.t9)("fetchFavoriteStickers",{hash:e});if(!t)return;const n=(0,a.Rd)();(0,a.R3)({...n,stickers:{...n.stickers,favorite:t}})}(t)})),(0,a.iw)("loadGreetingStickers",(async e=>{const{hash:t}=e.stickers.greeting||{},n=await(0,S.t9)("fetchStickersForEmoji",{emoji:"👋⭐️",hash:t});if(n)return e=(0,a.Rd)(),{...e,stickers:{...e.stickers,greeting:{hash:n.hash,stickers:n.stickers.filter((e=>"👋"===e.emoji))}}}})),(0,a.iw)("loadFeaturedStickers",(e=>{const{hash:t}=e.stickers.featured||{};!async function(e){const t=await(0,S.t9)("fetchFeaturedStickers",{hash:e});t&&(0,a.R3)((0,r.z3)((0,a.Rd)(),"featured",t.hash,t.sets))}(t)})),(0,a.iw)("loadStickers",((e,t,n)=>{const{stickerSetId:s,stickerSetShortName:i}=n;let{stickerSetAccessHash:o}=n;if(!o&&!i){const t=(0,c.Ny)(e,s);if(!t)return;o=t.accessHash}!async function(e,t,n){const s=await(0,S.t9)("fetchStickers",{stickerSetShortName:n,stickerSetId:e,accessHash:t});if(!s)return;const{set:i,stickers:o,packs:c}=s;let l=(0,a.Rd)();l=(0,r.Rg)(l,i.id,{...i,stickers:o,packs:c});const d=l.stickers.forEmoji.emoji;d&&c[d]&&(l=(0,r.vy)(l)),(0,a.R3)(l)}(s,o,i)})),(0,a.iw)("loadAnimatedEmojis",(()=>{!async function(){const e=await(0,S.t9)("fetchAnimatedEmojis");if(!e)return;const{set:t,stickers:n}=e;(0,a.R3)((0,r.g_)((0,a.Rd)(),{...t,stickers:n}))}(),async function(){const e=await(0,S.t9)("fetchAnimatedEmojiEffects");if(!e)return;const{set:t,stickers:n}=e;(0,a.R3)({...(0,a.Rd)(),animatedEmojiEffects:{...t,stickers:n}})}()})),(0,a.iw)("loadSavedGifs",(e=>{const{hash:t}=e.gifs.saved;!async function(e){const t=await(0,S.t9)("fetchSavedGifs",{hash:e});if(!t)return;const n=(0,a.Rd)();(0,a.R3)({...n,gifs:{...n.gifs,saved:t}})}(t)})),(0,a.iw)("saveGif",(async(e,t,n)=>{var s;const{gif:i,shouldUnsave:o}=n;if(!await(0,S.t9)("saveGif",{gif:i,shouldUnsave:o}))return;const r=(null===(s=(e=(0,a.Rd)()).gifs.saved.gifs)||void 0===s?void 0:s.filter((e=>{let{id:t}=e;return t!==i.id})))||[],c=o?r:[i,...r];return{...e,gifs:{...e.gifs,saved:{...e.gifs.saved,gifs:c}}}})),(0,a.iw)("faveSticker",((e,t,n)=>{const{sticker:a}=n;a&&(0,S.t9)("faveSticker",{sticker:a})})),(0,a.iw)("unfaveSticker",((e,t,n)=>{const{sticker:s}=n;s&&function(e){const t=(0,a.Rd)();(0,a.R3)({...t,stickers:{...t.stickers,favorite:{...t.stickers.favorite,stickers:t.stickers.favorite.stickers.filter((t=>{let{id:n}=t;return n!==e.id}))}}}),(0,S.t9)("faveSticker",{sticker:e,unfave:!0})}(s)})),(0,a.iw)("toggleStickerSet",((e,t,n)=>{const{stickerSetId:a}=n,s=(0,c.Ny)(e,a);if(!s)return;const{accessHash:i,installedDate:o}=s;(0,S.t9)(o?"uninstallStickerSet":"installStickerSet",{stickerSetId:a,accessHash:i})})),(0,a.iw)("loadEmojiKeywords",(async(e,t,n)=>{var s,i;const{language:o}=n;let r=e.emojiKeywords[o];if(null!==(s=r)&&void 0!==s&&s.isLoading)return;(0,a.R3)({...e,emojiKeywords:{...e.emojiKeywords,[o]:{...r,isLoading:!0}}});const c=await(0,S.t9)("fetchEmojiKeywords",{language:o,fromVersion:r?r.version:0});return r=(e=(0,a.Rd)()).emojiKeywords[o],c?{...e,emojiKeywords:{...e.emojiKeywords,[o]:{isLoading:!1,version:c.version,keywords:{...null===(i=r)||void 0===i?void 0:i.keywords,...c.keywords}}}}:{...e,emojiKeywords:{...e.emojiKeywords,[o]:{...r,isLoading:!1}}}})),(0,a.iw)("setStickerSearchQuery",((e,t,n)=>{const{query:s}=n;s&&A((()=>{!async function(e,t){const n=await(0,S.t9)("searchStickers",{query:e,hash:void 0});if(!n)return;const s=(0,a.Rd)(),{setsById:i,added:o}=s.stickers,c=n.sets.map((e=>{let{id:t}=e;return t}));o.setIds&&o.setIds.forEach((t=>{if(!c.includes(t)){const{title:n}=i[t]||{};n&&(0,B.Z)(n,e)&&c.unshift(t)}})),(0,a.R3)((0,r.z3)(s,"search",n.hash,n.sets,c))}(s)}))})),(0,a.iw)("setGifSearchQuery",((e,t,n)=>{const{query:a}=n;"string"==typeof a&&A((()=>{x(a)}))})),(0,a.iw)("searchMoreGifs",(e=>{const{query:t,offset:n}=e.gifs.search;"string"==typeof t&&A((()=>{x(t,n)}))})),(0,a.iw)("loadStickersForEmoji",((e,t,n)=>{const{emoji:s}=n,{hash:i}=e.stickers.forEmoji;A((()=>{!async function(e,t){let n=(0,a.Rd)();(0,a.R3)({...n,stickers:{...n.stickers,forEmoji:{...n.stickers.forEmoji,emoji:e}}});const s=await(0,S.t9)("fetchStickersForEmoji",{emoji:e,hash:t});n=(0,a.Rd)(),s&&n.stickers.forEmoji.emoji===e&&(n=(0,r.IM)(n,e,s.stickers,s.hash),(0,a.R3)(n))}(s,i)}))})),(0,a.iw)("clearStickersForEmoji",(e=>({...e,stickers:{...e.stickers,forEmoji:{}}}))),(0,a.iw)("openStickerSetShortName",((e,t,n)=>{const{stickerSetShortName:a}=n;return{...e,openedStickerSetShortName:a}}));var L=n(790);const O=(0,E.P2)((e=>e()),500,!1);async function U(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",n=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0,o=arguments.length>3?arguments[3]:void 0,l=arguments.length>4?arguments[4]:void 0,d=arguments.length>5?arguments[5]:void 0;if(o){const a=await(0,S.t9)("searchMessagesLocal",{chat:o,query:t,type:n,limit:s.Hk,offsetId:i,minDate:d,maxDate:l});if(a){const{messages:t,users:n,totalCount:s,nextOffsetId:i}=a;e={messages:t,users:n,chats:[],totalCount:s,nextRate:i}}}else e=await(0,S.t9)("searchMessagesGlobal",{query:t,offsetRate:i,limit:s.Hk,type:n,maxDate:l,minDate:d});let u=(0,a.Rd)();const m=(0,c.JX)(u);if(!e||""!==t&&t!==m)return void(0,a.R3)((0,r.xv)(u,{messages:!1}));const{messages:h,users:f,chats:p,totalCount:v,nextRate:I}=e;p.length&&(u=(0,r.fZ)(u,(0,g.ee)(p,"id"))),f.length&&(u=(0,r.Sh)(u,(0,g.ee)(f,"id"))),h.length&&(u=(0,r.m6)(u,h)),u=(0,r.px)(u,h,v,n,I),(0,a.R3)(u)}async function F(e,t,n){let i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const o=await(0,S.t9)("searchMessagesLocal",{chat:e,type:t,limit:2*s.EN,offsetId:n});if(!o)return;const{chats:l,users:d,messages:u,totalCount:m,nextOffsetId:h}=o,f=(0,g.ee)(u,"id"),p=Object.keys(f).map(Number);let v=(0,a.Rd)();const I=(0,c.we)(v);I&&(v=(0,r.fZ)(v,(0,g.ee)(l,"id")),v=(0,r.Sh)(v,(0,g.ee)(d,"id")),v=(0,r.c_)(v,e.id,f),v=(0,r.c1)(v,e.id,t,p,m,h),(0,a.R3)(v),i||F(e,t,h,!0))}(0,a.iw)("setGlobalSearchQuery",((e,t,n)=>{const{chatId:s}=e.globalSearch,{query:i}=n;i&&!s&&O((()=>{!async function(e){const t=await(0,S.t9)("searchChats",{query:e});let n=(0,a.Rd)();const s=(0,c.JX)(n);if(!t||!s||e!==s)return void(0,a.R3)((0,r.xv)(n,{chats:!1}));const{localChats:i,localUsers:o,globalChats:l,globalUsers:d}=t;(i.length||l.length)&&(n=(0,r.fZ)(n,(0,g.ee)([...i,...l],"id"))),(o.length||d.length)&&(n=(0,r.Sh)(n,(0,g.ee)([...o,...d],"id"))),n=(0,r.xv)(n,{chats:!1}),n=(0,r.No)(n,{localResults:{chatIds:i.map((e=>{let{id:t}=e;return t})),userIds:o.map((e=>{let{id:t}=e;return t}))},globalResults:{...n.globalSearch.globalResults,chatIds:l.map((e=>{let{id:t}=e;return t})),userIds:d.map((e=>{let{id:t}=e;return t}))}}),(0,a.R3)(n)}(i)}))})),(0,a.iw)("setGlobalSearchDate",((e,t,n)=>{const{date:s}=n,i=s?(0,L.IS)(s):s;e=(0,r.No)(e,{date:s,query:"",resultsByType:{...e.globalSearch.resultsByType,text:{totalCount:void 0,foundIds:[],nextOffsetId:0}}}),(0,a.R3)(e);const{chatId:o}=e.globalSearch;U("","text",void 0,o?(0,c.Z1)(e,o):void 0,i,s)})),(0,a.iw)("searchMessagesGlobal",((e,t,n)=>{var a;const{query:s,resultsByType:i,chatId:o,date:r}=e.globalSearch,l=r?(0,L.IS)(r):r,{type:d}=n;U(s,d,null==i||null===(a=i[d])||void 0===a?void 0:a.nextOffsetId,o?(0,c.Z1)(e,o):void 0,l,r)})),(0,a.iw)("searchTextMessagesLocal",(e=>{const{chatId:t,threadId:n}=(0,c.Bt)(e)||{},i=t?(0,c.Z1)(e,t):void 0,l=(0,c.n5)(e);if(!i||!l||!n)return;const{query:d,results:u}=l,m=null==u?void 0:u.nextOffsetId;let h;if(n!==o._f){const a=(0,c.tZ)(e,t,n);h=null==a?void 0:a.topMessageId}!async function(e,t,n,i,o){if(!i)return;const l=await(0,S.t9)("searchMessagesLocal",{chat:e,type:"text",query:i,topMessageId:n,limit:s.pn,offsetId:o});if(!l)return;const{chats:d,users:u,messages:m,totalCount:h,nextOffsetId:f}=l,p=(0,g.ee)(m,"id"),v=Object.keys(p).map(Number);let I=(0,a.Rd)();const y=(0,c.n5)(I);y&&i===y.query&&(I=(0,r.fZ)(I,(0,g.ee)(d,"id")),I=(0,r.Sh)(I,(0,g.ee)(u,"id")),I=(0,r.c_)(I,e.id,p),I=(0,r.dx)(I,e.id,t,v,h,f),(0,a.R3)(I))}(i,n,h,d,m)})),(0,a.iw)("searchMediaMessagesLocal",(e=>{const{chatId:t}=(0,c.Bt)(e)||{};if(!t)return;const n=(0,c.Z1)(e,t),a=(0,c.we)(e);if(!n||!a)return;const{currentType:s,resultsByType:i}=a,o=s&&i&&i[s],r=null==o?void 0:o.nextOffsetId;s&&F(n,s,r)})),(0,a.iw)("searchMessagesByDate",((e,t,n)=>{const{timestamp:s}=n,{chatId:i}=(0,c.Bt)(e)||{};if(!i)return;const o=(0,c.Z1)(e,i);o&&async function(e,t){const n=await(0,S.t9)("findFirstMessageIdAfterDate",{chat:e,timestamp:t});n&&(0,a.Sv)().focusMessage({chatId:e.id,messageId:n})}(o,s)})),(0,a.iw)("checkPublicLink",(async(e,t,n)=>{const{chatId:s}=(0,c.Bt)(e)||{};if(!s)return;if(e.management.progress===m.wv.InProgress)return;const{username:i}=n;e=(0,r.H9)(e,m.wv.InProgress),e=(0,r.fw)(e,s,{isUsernameAvailable:void 0}),(0,a.R3)(e);const o=await(0,S.t9)("checkChatUsername",{username:i});return e=(0,a.Rd)(),e=(0,r.H9)(e,o?m.wv.Complete:m.wv.Error),(0,r.fw)(e,s,{isUsernameAvailable:o})})),(0,a.iw)("updatePublicLink",(async(e,t,n)=>{const{chatId:s}=(0,c.Bt)(e)||{};let i=s&&(0,c.Z1)(e,s);if(!s||!i)return;const{username:o}=n;if(e=(0,r.H9)(e,m.wv.InProgress),(0,a.R3)(e),(0,d.G9)(i)){if(i=await(0,S.t9)("migrateChat",i),!i)return;t.openChat({id:i.id})}const l=await(0,S.t9)("setChatUsername",{chat:i,username:o});return e=(0,a.Rd)(),e=(0,r.H9)(e,l?m.wv.Complete:m.wv.Error),(0,r.fw)(e,s,{isUsernameAvailable:void 0})})),(0,a.iw)("updatePrivateLink",(e=>{const{chatId:t}=(0,c.Bt)(e)||{},n=t&&(0,c.Z1)(e,t);t&&n&&(0,S.t9)("updatePrivateLink",{chat:n})})),(0,a.iw)("setEditingExportedInvite",((e,t,n)=>{const{chatId:s,invite:i}=n;(0,a.R3)((0,r.fw)(e,s,{editingInvite:i}))})),(0,a.iw)("setOpenedInviteInfo",((e,t,n)=>{const{chatId:s,invite:i}=n,o=i?{inviteInfo:{invite:i}}:{inviteInfo:void 0};(0,a.R3)((0,r.fw)(e,s,o))})),(0,a.iw)("loadExportedChatInvites",(async(e,t,n)=>{const{chatId:s,adminId:i,isRevoked:o,limit:l}=n,d=(0,c.Z1)(e,s),u=(0,c.dy)(e,i||e.currentUserId);if(!d||!u)return;const m=await(0,S.t9)("fetchExportedChatInvites",{peer:d,admin:u,isRevoked:o,limit:l});if(!m)return;const h=o?{revokedInvites:m}:{invites:m};return(0,r.fw)((0,a.Rd)(),s,h)})),(0,a.iw)("editExportedChatInvite",(async(e,t,n)=>{const{chatId:s,link:i,isRevoked:o,expireDate:l,usageLimit:d,isRequestNeeded:u,title:m}=n,h=(0,c.Z1)(e,s);if(!h)return;const g=await(0,S.t9)("editExportedChatInvite",{peer:h,link:i,isRevoked:o,expireDate:l,usageLimit:d,isRequestNeeded:u,title:m});if(!g)return;const{oldInvite:f,newInvite:p}=g,v=((e=(0,a.Rd)()).management.byChatId[s].invites||[]).filter((e=>e.link!==f.link)),I=[...e.management.byChatId[s].revokedInvites||[]];return p.isRevoked?I.unshift(p):v.push(p),(0,r.fw)(e,s,{invites:v,revokedInvites:I})})),(0,a.iw)("exportChatInvite",(async(e,t,n)=>{const{chatId:s,expireDate:i,usageLimit:o,isRequestNeeded:l,title:d}=n,u=(0,c.Z1)(e,s);if(!u)return;const m=await(0,S.t9)("exportChatInvite",{peer:u,expireDate:i,usageLimit:o,isRequestNeeded:l,title:d});if(!m)return;const h=(e=(0,a.Rd)()).management.byChatId[s].invites||[];return(0,r.fw)(e,s,{invites:[...h,m]})})),(0,a.iw)("deleteExportedChatInvite",(async(e,t,n)=>{var s,i;const{chatId:o,link:l}=n,d=(0,c.Z1)(e,o);if(!d)return;if(!await(0,S.t9)("deleteExportedChatInvite",{peer:d,link:l}))return;const u=(e=(0,a.Rd)()).management.byChatId[o];return(0,r.fw)(e,o,{invites:null==u||null===(s=u.invites)||void 0===s?void 0:s.filter((e=>e.link!==l)),revokedInvites:null==u||null===(i=u.revokedInvites)||void 0===i?void 0:i.filter((e=>e.link!==l))})})),(0,a.iw)("deleteRevokedExportedChatInvites",(async(e,t,n)=>{const{chatId:s,adminId:i}=n,o=(0,c.Z1)(e,s),l=(0,c.dy)(e,i||e.currentUserId);if(o&&l)return await(0,S.t9)("deleteRevokedExportedChatInvites",{peer:o,admin:l})?(e=(0,a.Rd)(),(0,r.fw)(e,s,{revokedInvites:[]})):void 0})),(0,a.iw)("loadChatInviteImporters",(async(e,t,n)=>{var s;const{chatId:i,link:o,offsetDate:l,offsetUserId:d,limit:u}=n,m=(0,c.Z1)(e,i),h=(0,c.dy)(e,d);if(!m||d&&!h)return;const g=await(0,S.t9)("fetchChatInviteImporters",{peer:m,link:o,offsetDate:l,offsetUser:h,limit:u});if(!g)return;const f=null===(s=(e=(0,a.Rd)()).management.byChatId[i])||void 0===s?void 0:s.inviteInfo;return null!=f&&f.invite&&f.invite.link===o?(0,r.fw)(e,i,{inviteInfo:{...f,importers:g}}):void 0})),(0,a.iw)("loadChatInviteRequesters",(async(e,t,n)=>{var s;const{chatId:i,link:o,offsetDate:l,offsetUserId:d,limit:u}=n,m=(0,c.Z1)(e,i),h=(0,c.dy)(e,d);if(!m||d&&!h)return;const g=await(0,S.t9)("fetchChatInviteImporters",{peer:m,link:o,offsetDate:l,offsetUser:h,limit:u,isRequested:!0});if(!g)return;const f=null===(s=(e=(0,a.Rd)()).management.byChatId[i])||void 0===s?void 0:s.inviteInfo;return null!=f&&f.invite&&f.invite.link===o?(0,r.fw)(e,i,{inviteInfo:{...f,requesters:g}}):void 0})),(0,a.iw)("loadChatJoinRequests",(async(e,t,n)=>{const{chatId:s,offsetDate:i,offsetUserId:o,limit:l}=n,d=(0,c.Z1)(e,s),u=(0,c.dy)(e,o);if(!d||o&&!u)return;const m=await(0,S.t9)("fetchChatInviteImporters",{peer:d,offsetDate:i,offsetUser:u,limit:l,isRequested:!0});return m?(e=(0,a.Rd)(),(0,r.a4)(e,s,{joinRequests:m})):void 0})),(0,a.iw)("hideChatJoinRequest",(async(e,t,n)=>{var s;const{chatId:i,userId:o,isApproved:l}=n,d=(0,c.Z1)(e,i),u=(0,c.dy)(e,o);if(!d||!u)return;if(!await(0,S.t9)("hideChatJoinRequest",{peer:d,user:u,isApproved:l}))return;e=(0,a.Rd)();const m=(0,c.Z1)(e,i);return m?(0,r.a4)(e,i,{joinRequests:null===(s=m.joinRequests)||void 0===s?void 0:s.filter((e=>e.userId!==o))}):void 0})),(0,a.iw)("hideAllChatJoinRequests",(async(e,t,n)=>{const{chatId:s,isApproved:i,link:o}=n,l=(0,c.Z1)(e,s);if(!l)return;if(!await(0,S.t9)("hideAllChatJoinRequests",{peer:l,isApproved:i,link:o}))return;e=(0,a.Rd)();const d=(0,c.Z1)(e,s);return d?(0,r.a4)(e,s,{joinRequests:[],fullInfo:{...d.fullInfo,recentRequesterIds:[],requestsPending:0}}):void 0})),(0,a.iw)("hideChatReportPanel",(async(e,t,n)=>{const{chatId:s}=n,i=(0,c.Z1)(e,s);if(i)return await(0,S.t9)("hideChatReportPanel",i)?(0,r.a4)((0,a.Rd)(),s,{settings:void 0}):void 0}));var D=n(6974);let $;function q(e){return(0,S.t9)("fetchMessages",{chat:e,threadId:o._f,offsetId:e.lastReadInboxMessageId,addOffset:-(Math.round(s.hT/2)+1),limit:s.hT})}(0,a.iw)("sync",(()=>{s.eM&&console.log(">>> START SYNC"),$&&clearTimeout($),(0,a.R3)({...(0,a.Rd)(),isSyncing:!0}),$=window.setTimeout((()=>{(0,a.R3)({...(0,a.Rd)(),isSyncing:!1}),$=void 0}),15e3);const{loadAllChats:e,preloadTopChatMessages:t}=(0,a.Sv)();e({listType:"active",shouldReplace:!0,onReplace:async()=>{await async function(){let e=!1,t=(0,a.Rd)();const n=Object.keys(t.messages.byChatId).reduce(((e,n)=>(e[n]={},e[n].draft=(0,c.Ms)(t,n,o._f),e[n].editingId=(0,c._$)(t,n,o._f),e[n].editingDraft=(0,c.s)(t,n,o._f),e)),{}),{chatId:i,threadId:l}=(0,c.Bt)(t)||{},d=i?t.chats.byId[i]:void 0;if(i&&d){const n=await q(d);t=(0,a.Rd)();const{chatId:u}=(0,c.Bt)(t)||{},m=l&&(0,c.tZ)(t,i,l);if(n&&u===i){const a=t.messages.byChatId[i],c=i===s.aw?t.serviceNotifications.map((e=>{let{message:t}=e;return t})):[],d=[].concat(n.messages,c),u=(0,g.ee)(d,"id"),h=Object.keys(u).map(Number);if(t={...t,messages:{...t.messages,byChatId:{}}},t=(0,r.c_)(t,i,u),t=(0,r.xj)(t,i,o._f,h),t=(0,r.y9)(t,i,o._f,h),l&&m&&m.originChannelId){const{originChannelId:e}=m,n=t.messages.byChatId[e],s=await q(t.chats.byId[e]);if(s){const e=(0,g.ee)(s.messages,"id"),r=Object.keys(e).map(Number);t={...t,messages:{...t.messages,byChatId:{...t.messages.byChatId,[m.originChannelId]:{byId:e,threadsById:{[o._f]:{...null==n?void 0:n.threadsById[o._f],listedIds:r,viewportIds:r,outlyingIds:void 0}}},[i]:{...t.messages.byChatId[i],threadsById:{...t.messages.byChatId[i].threadsById,[l]:{...null==a?void 0:a.threadsById[l],outlyingIds:void 0}}}}}}}}t=(0,r.GL)(t,(0,g.ee)(n.chats,"id")),t=(0,r.eD)(t,(0,g.ee)(n.users,"id")),t=(0,r.j6)(t,i,n.threadInfos),e=!0}}e||(t={...t,messages:{...t.messages,byChatId:{}}}),Object.keys(n).forEach((e=>{t=(0,r.sN)(t,e,o._f,n[e])})),(0,a.R3)(t);const{chatId:u,messageId:m}=t.audioPlayer;u&&m&&!(0,c.hj)(t,u,m)&&(0,a.Sv)().closeAudioPlayer()}(),(0,a.R3)({...(0,a.Rd)(),lastSyncTime:Date.now(),isSyncing:!1}),s.eM&&console.log(">>> FINISH SYNC"),(0,D.S1)(),e({listType:"archived",shouldReplace:!0}),(0,S.t9)("fetchCurrentUser"),t()}})}));const j=(0,E.Ds)((e=>e()),500,!1,!0),G=(0,E.P2)((e=>e()),500,!1);function H(e,t,n){return{...e,inlineBots:{...e.inlineBots,byUsername:{...e.inlineBots.byUsername,[t]:n}}}}function _(e,t){return{...e,inlineBots:{...e.inlineBots,isLoading:t}}}(0,a.iw)("loadFullUser",((e,t,n)=>{const{userId:a}=n,s=(0,c.dy)(e,a);if(!s)return;const{id:i,accessHash:o}=s;j((()=>(0,S.t9)("fetchFullUser",{id:i,accessHash:o})))})),(0,a.iw)("loadUser",(async(e,t,n)=>{const{userId:s}=n,i=(0,c.dy)(e,s);if(!i)return;const o=await(0,S.t9)("fetchUsers",{users:[i]});if(!o)return;const{users:l,userStatusesById:d}=o;return e=(0,a.Rd)(),e=(0,r.eD)(e,(0,g.ee)(l,"id")),(0,r.ps)(e,{...e.users.statusesById,...d})})),(0,a.iw)("loadTopUsers",(e=>{const{topPeers:{lastRequestedAt:t}}=e;(!t||(0,f.b)(e.serverTimeOffset)-t>60)&&async function(){const e=await(0,S.t9)("fetchTopUsers");if(!e)return;const{ids:t,users:n}=e;let s=(0,a.Rd)();s=(0,r.Sh)(s,(0,g.ee)(n,"id")),s={...s,topPeers:{...s.topPeers,userIds:t,lastRequestedAt:(0,f.b)(s.serverTimeOffset)}},(0,a.R3)(s)}()})),(0,a.iw)("loadContactList",(()=>{!async function(){const e=await(0,S.t9)("fetchContactList");if(!e)return;let t=(0,r.Sh)((0,a.Rd)(),(0,g.ee)(e.users,"id"));t=(0,r.fZ)(t,(0,g.ee)(e.chats,"id"));const n=e=>e.lastName||e.firstName||"",s=new Intl.Collator("en-US"),i=e.users.sort(((e,t)=>s.compare(n(e),n(t)))).filter((e=>!e.isSelf));(0,a.R3)({...t,contactList:{userIds:i.map((e=>e.id))}})}()})),(0,a.iw)("loadCurrentUser",(()=>{(0,S.t9)("fetchCurrentUser")})),(0,a.iw)("loadCommonChats",(async e=>{var t,n,s;const{chatId:i}=(0,c.Bt)(e)||{},o=i?(0,c.dy)(e,i):void 0;if(!o||(0,d.cS)(o)||null!==(t=o.commonChats)&&void 0!==t&&t.isFullyLoaded)return;const l=null===(n=o.commonChats)||void 0===n?void 0:n.maxId,u=await(0,S.t9)("fetchCommonChats",o.id,o.accessHash,l);if(!u)return;const{chats:m,chatIds:h,isFullyLoaded:f}=u;return e=(0,a.Rd)(),m.length&&(e=(0,r.fZ)(e,(0,g.ee)(m,"id"))),(0,r.Nq)(e,o.id,{commonChats:{maxId:h.length?h[h.length-1]:"0",ids:(0,g.Tw)(((null===(s=o.commonChats)||void 0===s?void 0:s.ids)||[]).concat(h)),isFullyLoaded:f}})})),(0,a.iw)("updateContact",((e,t,n)=>{const{userId:s,isMuted:i=!1,firstName:o,lastName:l,shouldSharePhoneNumber:d}=n;!async function(e,t,n,s,i){let o=(0,a.Rd)();const l=(0,c.dy)(o,e);if(!l)return;let d;if((0,a.Sv)().updateChatMutedState({chatId:e,isMuted:t}),(0,a.R3)((0,r.H9)((0,a.Rd)(),m.wv.InProgress)),!l.isContact&&l.phoneNumber)d=await(0,S.t9)("importContact",{phone:l.phoneNumber,firstName:n,lastName:s});else{const{id:e,accessHash:t}=l;d=await(0,S.t9)("updateContact",{id:e,accessHash:t,phoneNumber:"",firstName:n,lastName:s,shouldSharePhoneNumber:i})}o=(0,a.Rd)(),d&&(0,a.R3)((0,r.Nq)(o,l.id,{firstName:n,lastName:s})),o=(0,r.H9)(o,m.wv.Complete),o=(0,r.ft)(o),(0,a.R3)(o)}(s,i,o,l,d)})),(0,a.iw)("deleteContact",((e,t,n)=>{const{userId:s}=n;!async function(e){const t=(0,a.Rd)(),n=(0,c.dy)(t,e);if(!n)return;const{id:s,accessHash:i}=n;await(0,S.t9)("deleteContact",{id:s,accessHash:i})}(s)})),(0,a.iw)("loadProfilePhotos",(async(e,t,n)=>{const{profileId:s}=n,i=(0,d.YC)(s),o=i?(0,c.dy)(e,s):void 0,l=i?void 0:(0,c.Z1)(e,s);if(!o&&!l)return;const u=await(0,S.t9)("fetchProfilePhotos",o,l);return u&&u.photos?(e=(0,a.Rd)(),i?e=(0,r.Nq)(e,s,{photos:u.photos}):(e=(0,r.Sh)(e,(0,g.ee)(u.users,"id")),e=(0,r.a4)(e,s,{photos:u.photos})),e):void 0})),(0,a.iw)("setUserSearchQuery",((e,t,n)=>{const{query:s}=n;s&&G((()=>{!async function(e){const t=await(0,S.t9)("searchChats",{query:e});let n=(0,a.Rd)();const s=n.userSearch.query;if(!t||!s||e!==s)return void(0,a.R3)((0,r.Q3)(n,!1));const{localUsers:i,globalUsers:o}=t;let c,l;i.length&&(n=(0,r.Sh)(n,(0,g.ee)(i,"id")),c=i.map((e=>{let{id:t}=e;return t}))),o.length&&(n=(0,r.Sh)(n,(0,g.ee)(o,"id")),l=o.map((e=>{let{id:t}=e;return t}))),n=(0,r.Q3)(n,!1),n=(0,r.Lm)(n,{localUserIds:c,globalUserIds:l}),(0,a.R3)(n)}(s)}))})),(0,a.iw)("importContact",(async(e,t,n)=>{const{phoneNumber:s,firstName:i,lastName:o}=n,c=await(0,S.t9)("importContact",{phone:s,firstName:i,lastName:o});if(c)return t.openChat({id:c}),(0,r.ft)((0,a.Rd)());t.showNotification({message:I.i0("Contacts.PhoneNumber.NotRegistred")})})),(0,a.iw)("reportSpam",((e,t,n)=>{const{chatId:a}=n,s=(0,d.YC)(a)?(0,c.dy)(e,a):(0,c.Z1)(e,a);s&&(0,S.t9)("reportSpam",s)}));const z=(0,E.Ds)((e=>e()),500,!1);async function V(e,t,n,a,s){await(0,S.t9)("sendMessage",{chat:e,text:n,replyingTo:a,sendAs:s})}(0,a.iw)("clickInlineButton",((e,t,n)=>{const{button:i}=n;switch(i.type){case"command":t.sendBotCommand({command:i.value});break;case"url":i.value.match(s.FS)||i.value.match(s.g$)?t.openTelegramLink({url:i.value}):t.toggleSafeLinkModal({url:i.value});break;case"callback":{const t=(0,c.jr)(e);if(!t)return;!async function(e,t,n){const s=await(0,S.t9)("answerCallbackButton",{chatId:e.id,accessHash:e.accessHash,messageId:t,data:n});if(!s)return;const{showDialog:i,showNotification:o,toggleSafeLinkModal:r}=(0,a.Sv)(),{message:c,alert:l,url:d}=s;l?i({data:{message:c||"Error"}}):c?o({message:c}):d&&r({url:d})}(t,i.messageId,i.value);break}case"requestPoll":t.openPollModal();break;case"requestSelfContact":{const n=e.currentUserId?(0,c.dy)(e,e.currentUserId):void 0;if(!n)return;t.showDialog({data:{phoneNumber:n.phoneNumber,firstName:n.firstName,lastName:n.lastName,userId:n.id}});break}case"buy":{const n=(0,c.jr)(e),{messageId:a,value:s}=i;if(!n)return;s?t.getReceipt({receiptMessageId:s,chatId:n.id,messageId:a}):(t.getPaymentForm({chat:n,messageId:a}),t.setInvoiceMessageInfo((0,c.hj)(e,n.id,a)),t.openPaymentModal({chatId:n.id,messageId:a}));break}}})),(0,a.iw)("sendBotCommand",((e,t,n)=>{const{command:a,chatId:s}=n,{currentUserId:i}=e,o=s?(0,c.Z1)(e,s):(0,c.jr)(e),r=(0,c.Bt)(e);if(!i||!o||!r)return;const{threadId:l}=r;t.setReplyingToId({messageId:void 0}),t.clearWebPagePreview({chatId:o.id,threadId:l,value:!1}),V(o,0,a,(0,c.Yy)(e,o.id,l),(0,c._5)(e,s))})),(0,a.iw)("restartBot",(async(e,t,n)=>{const{chatId:s}=n,{currentUserId:i}=e,o=(0,c.jr)(e),l=i&&(0,c.IK)(e,s);i&&o&&l&&await(0,S.t9)("unblockContact",l.id,l.accessHash)&&((0,a.R3)((0,r.rB)((0,a.Rd)(),l.id)),V(o,0,"/start",void 0,(0,c._5)(e,s)))})),(0,a.iw)("loadTopInlineBots",(async e=>{const{lastRequestedAt:t}=e.topInlineBots;if(t&&(0,f.b)(e.serverTimeOffset)-t<60)return;const n=await(0,S.t9)("fetchTopInlineBots");if(!n)return;const{ids:s,users:i}=n;return e=(0,a.Rd)(),e=(0,r.Sh)(e,(0,g.ee)(i,"id")),{...e,topInlineBots:{...e.topInlineBots,userIds:s,lastRequestedAt:(0,f.b)(e.serverTimeOffset)}}})),(0,a.iw)("queryInlineBot",(async(e,t,n)=>{const{chatId:s,username:i,query:o,offset:l}=n;let d=e.inlineBots.byUsername[i];if(!1!==d){if(void 0===d){const{user:t,chat:n}=await(0,S.t9)("fetchInlineBot",{username:i})||{};if(e=(0,a.Rd)(),!t||!n)return void(0,a.R3)(H(e,i,!1));e=(0,r.Sh)(e,{[t.id]:t}),e=(0,r.fZ)(e,{[n.id]:n}),d={id:t.id,query:"",offset:"",switchPm:void 0,canLoadMore:!0,results:[]},e=H(e,i,d),(0,a.R3)(e)}(o!==d.query||d.canLoadMore)&&z((()=>{!async function(e){let{username:t,inlineBotData:n,chatId:s,query:i,offset:o}=e,r=(0,a.Rd)();const l=(0,c.dy)(r,n.id),d=(0,c.Z1)(r,s);if(!l||!d)return;const u=n.query!==i;r=_(r,!0),r=H(r,t,{...n,query:i,...u&&{offset:void 0,results:[]}}),(0,a.R3)(r);const m=await(0,S.t9)("fetchInlineBotResults",{bot:l,chat:d,query:i,offset:u?void 0:o}),h=r.inlineBots.byUsername[t];if(r=_((0,a.Rd)(),!1),!m||!h||i!==h.query)return void(0,a.R3)(r);const g=new Set((h.results||[]).map((e=>e.id))),f=m.results.filter((e=>!g.has(e.id)));r=H(r,t,{...h,help:m.help,...f.length&&{isGallery:m.isGallery},...m.switchPm&&{switchPm:m.switchPm},canLoadMore:m.results.length>0&&Boolean(m.nextOffset),results:""===h.offset||h.offset===m.nextOffset?m.results:(h.results||[]).concat(f),offset:f.length?m.nextOffset:""}),(0,a.R3)(r)}({username:i,inlineBotData:d,chatId:s,query:o,offset:l})}))}})),(0,a.iw)("sendInlineBotResult",((e,t,n)=>{const{id:a,queryId:s,isSilent:i,scheduledAt:o}=n,r=(0,c.Bt)(e);if(!r||!a)return;const{chatId:l,threadId:d}=r,u=(0,c.Z1)(e,l);t.setReplyingToId({messageId:void 0}),t.clearWebPagePreview({chatId:l,threadId:d,value:!1}),(0,S.t9)("sendInlineBotResult",{chat:u,resultId:a,queryId:s,replyingTo:(0,c.Yy)(e,l,d),sendAs:(0,c._5)(e,l),isSilent:i,scheduleDate:o})})),(0,a.iw)("resetInlineBot",((e,t,n)=>{const{username:s}=n;let i=e.inlineBots.byUsername[s];i&&(i={id:i.id,query:"",offset:"",switchPm:void 0,canLoadMore:!0,results:[]},(0,a.R3)(H(e,s,i)))})),(0,a.iw)("startBot",(async(e,t,n)=>{const{botId:a,param:s}=n,i=(0,c.dy)(e,a);i&&await(0,S.t9)("startBot",{bot:i,startParam:s})})),n(1371),(0,a.iw)("loadPasswordInfo",(async e=>{const t=await(0,S.t9)("getPasswordInfo");if(t)return e=(0,a.Rd)(),e=(0,r.BI)(e,{hasPassword:t.hasPassword}),(0,r.IE)(e,{hint:t.hint})})),(0,a.iw)("checkPassword",(async(e,t,n)=>{const{currentPassword:s,onSuccess:i}=n;(0,a.R3)((0,r.IE)(e,{isLoading:!0,error:void 0}));const o=await(0,S.t9)("checkPassword",s);(0,a.R3)((0,r.IE)((0,a.Rd)(),{isLoading:!1})),o&&i()})),(0,a.iw)("clearPassword",(async(e,t,n)=>{const{currentPassword:s,onSuccess:i}=n;(0,a.R3)((0,r.IE)(e,{isLoading:!0,error:void 0}));const o=await(0,S.t9)("clearPassword",s);(0,a.R3)((0,r.IE)((0,a.Rd)(),{isLoading:!1})),o&&i()})),(0,a.iw)("updatePassword",(async(e,t,n)=>{const{currentPassword:s,password:i,hint:o,email:c,onSuccess:l}=n;(0,a.R3)((0,r.IE)(e,{isLoading:!0,error:void 0}));const d=await(0,S.t9)("updatePassword",s,i,o,c);(0,a.R3)((0,r.IE)((0,a.Rd)(),{isLoading:!1})),d&&l()})),(0,a.iw)("updateRecoveryEmail",(async(e,t,n)=>{const{currentPassword:s,email:i,onSuccess:o}=n;(0,a.R3)((0,r.IE)(e,{isLoading:!0,error:void 0}));const c=await(0,S.t9)("updateRecoveryEmail",s,i);(0,a.R3)((0,r.IE)((0,a.Rd)(),{isLoading:!1,waitingEmailCodeLength:void 0})),c&&o()})),(0,a.iw)("provideTwoFaEmailCode",((e,t,n)=>{const{code:a}=n;(0,S.t9)("provideRecoveryEmailCode",a)})),(0,a.iw)("clearTwoFaError",(e=>(0,r.IE)(e,{error:void 0}))),(0,a.iw)("validateRequestedInfo",((e,t,n)=>{const{requestInfo:s,saveInfo:i}=n,o=(0,c.gx)(e),l=o&&(0,c.Z1)(e,o),d=(0,c.Mz)(e);l&&d&&async function(e,t,n,s){const i=await(0,S.t9)("validateRequestedInfo",{chat:e,messageId:t,requestInfo:n,shouldSave:s});if(!i)return;const{id:o,shippingOptions:c}=i;if(!o)return;let l=(0,r.vT)((0,a.Rd)(),o);c?(l=(0,r.TM)(l,c),l=(0,r.Q$)(l,m.KB.Shipping)):l=(0,r.Q$)(l,m.KB.PaymentInfo),(0,a.R3)(l)}(l,d,s,i)})),(0,a.iw)("getPaymentForm",((e,t,n)=>{const{chat:s,messageId:i}=n;s&&i&&async function(e,t){const n=await(0,S.t9)("getPaymentForm",{chat:e,messageId:t});if(!n)return;let s=(0,r._7)((0,a.Rd)(),n),i=m.KB.PaymentInfo;s.payment.invoice&&(s.payment.invoice.shippingAddressRequested||s.payment.invoice.nameRequested||s.payment.invoice.phoneRequested||s.payment.invoice.emailRequested)&&(i=m.KB.ShippingInfo),s=(0,r.Q$)(s,i),(0,a.R3)(s)}(s,i)})),(0,a.iw)("getReceipt",((e,t,n)=>{const{receiptMessageId:s,chatId:i,messageId:o}=n,l=i&&(0,c.Z1)(e,i);o&&s&&l&&async function(e,t,n){const s=await(0,S.t9)("getReceipt",e,n);if(!s)return;let i=(0,a.Rd)();const o=(0,c.hj)(i,e.id,t);i=(0,r.Dq)(i,s,o),(0,a.R3)(i)}(l,o,s)})),(0,a.iw)("clearPaymentError",(e=>{(0,a.R3)({...e,payment:{...e.payment,error:void 0}})})),(0,a.iw)("clearReceipt",(e=>{(0,a.R3)({...e,payment:{...e.payment,receipt:void 0}})})),(0,a.iw)("sendCredentialsInfo",((e,t,n)=>{const{nativeProvider:i}=e.payment,{credentials:o}=n,{data:l}=o;if("stripe"===i){const t=(0,c.$$)(e);if(!t)return;!async function(e,t){const n=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}),s=await fetch(`https://api.stripe.com/v1/tokens${n}`,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Bearer ${t}`}}),i=await s.json();if(i.error){const e=(0,d.Ow)(i.error),t=(0,a.Rd)();return void(0,a.R3)({...t,payment:{...t.payment,error:{...e}}})}let o=(0,r.QH)((0,a.Rd)(),{type:i.type,id:i.id});o=(0,r.Q$)(o,m.KB.Checkout),(0,a.R3)(o)}(l,t)}else if("smartglocal"===i){const t=(0,c.EB)(e);if(!t)return;!async function(e,t){const n={card:{number:e.cardNumber.replace(/[^\d]+/g,""),expiration_month:e.expiryMonth,expiration_year:e.expiryYear,security_code:e.cvv.replace(/[^\d]+/g,"")}},i=s.eA?"https://tgb-playground.smart-glocal.com/cds/v1/tokenize/card":"https://tgb.smart-glocal.com/cds/v1/tokenize/card",o=await fetch(i,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-PUBLIC-TOKEN":t},body:JSON.stringify(n)}),c=await o.json();if("ok"!==c.status){const e={description:"payment error"},t=(0,a.Rd)();return void(0,a.R3)({...t,payment:{...t.payment,error:{...e}}})}let l=(0,r.QD)((0,a.Rd)(),{type:"card",token:c.data.token});l=(0,r.Q$)(l,m.KB.Checkout),(0,a.R3)(l)}(l,t)}})),(0,a.iw)("sendPaymentForm",((e,t,n)=>{const{shippingOptionId:s,saveCredentials:i}=n,o=(0,c.gx)(e),l=o&&(0,c.Z1)(e,o),d=(0,c.Mz)(e),u=(0,c.eh)(e),m=(0,c.sp)(e),{nativeProvider:h}=e.payment,g="stripe"===h?(0,c.$$)(e):(0,c.EB)(e);l&&d&&g&&u&&h&&async function(e,t,n,s,i,o,c){if(!0===await(0,S.t9)("sendPaymentForm",{chat:e,messageId:t,formId:s,credentials:i,requestedInfoId:o,shippingOptionId:c})){const e=(0,r.bp)((0,a.Rd)());(0,a.R3)((0,r.WY)(e))}}(l,d,0,u,{save:i,data:"stripe"===h?(0,c.i3)(e):(0,c.Jg)(e)},m,s)})),(0,a.iw)("setPaymentStep",(function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(0,r.Q$)(e,n.step||m.KB.ShippingInfo)})),(0,a.iw)("setInvoiceMessageInfo",((e,t,n)=>(0,r.nA)(e,n)));var X=n(647),K=n(4907);const W=728,Y=424,J=288;var Q=n(3858);function ee(e,t){return t-(e.isLeftColumnShown&&!h.wB?e.leftColumnWidth||((n=Q.Z.get().width)>s._m?Math.min(Math.max(.25*n,J),.33*n):n>s.ks?Math.min(Math.max(.33*n,J),.4*n):Y):0);var n}let te=0;(0,a.iw)("loadAvailableReactions",(async()=>{const e=await(0,S.t9)("getAvailableReactions");if(e)return e.forEach((e=>{e.aroundAnimation&&X.he(`sticker${e.aroundAnimation.id}`,o.IU.Lottie),e.centerIcon&&X.he(`sticker${e.centerIcon.id}`,o.IU.Lottie)})),{...(0,a.Rd)(),availableReactions:e}})),(0,a.iw)("interactWithAnimatedEmoji",((e,t,n)=>{const{emoji:a,x:s,y:i,localEffect:o,startSize:r,isReversed:c}=n,l={id:te++,animatedEffect:a||o,x:ee(e,s)+40*Math.random()-20,y:i+40*Math.random()-20,startSize:r,isReversed:c};return{...e,activeEmojiInteractions:[...e.activeEmojiInteractions||[],l]}})),(0,a.iw)("sendEmojiInteraction",((e,t,n)=>{const{messageId:a,chatId:s,emoji:i,interactions:o,localEffect:r}=n,l=(0,c.Z1)(e,s);l&&(i||r)&&s!==e.currentUserId&&(0,S.t9)("sendEmojiInteraction",{chat:l,messageId:a,emoticon:i||(0,c.ji)(r),timestamps:o})})),(0,a.iw)("sendDefaultReaction",((e,t,n)=>{const{chatId:a,messageId:s,x:i,y:o}=n,r=(0,c.q6)(e,a),l=(0,c.hj)(e,a,s);r&&l&&!(0,d.CI)(l)&&t.sendReaction({chatId:a,messageId:s,reaction:r,x:i,y:o})})),(0,a.iw)("sendReaction",((e,t,n)=>{var a,i,o;const{chatId:r}=n;let{messageId:l}=n,{reaction:d}=n;const u=(0,c.Z1)(e,r);let m=(0,c.hj)(e,r,l);if(!u||!m)return;const h=Boolean(m.groupedId)&&!m.isInAlbum,f=h?(0,c.xH)(e,r,m.groupedId)[0]:void 0;m=h&&(0,c.hj)(e,r,f)||m,l=(null===(a=m)||void 0===a?void 0:a.id)||l,null!==(i=m.reactions)&&void 0!==i&&null!==(o=i.results)&&void 0!==o&&o.some((e=>e.reaction===d&&e.isChosen))&&(d=void 0),(0,S.t9)("sendReaction",{chat:u,messageId:l,reaction:d});const{animationLevel:p}=e.settings.byKey;return p===s.zy&&(e={...e,activeReactions:{...d?e.activeReactions:(0,g.CE)(e.activeReactions,[l]),...d&&{[l]:{reaction:d,messageId:l}}}}),function(e,t,n,a){const{reactions:s}=(0,c.hj)(e,t,n)||{};if(!s)return e;let i=s.results.map((e=>e.reaction===a?{...e,count:e.isChosen?e.count:e.count+1,isChosen:!0}:e.isChosen?{...e,isChosen:!1,count:e.count-1}:e)).filter((e=>e.count>0)),{recentReactions:o}=s;if(a&&!i.some((e=>e.reaction===a))){const{currentUserId:t}=e;i=[...i,{reaction:a,isChosen:!0,count:1}],s.canSeeList&&(o=[...o||[],{userId:t,reaction:a}])}return(0,K.cY)(e,t,n,{reactions:{...s,results:i,recentReactions:o}})}(e,r,l,d)})),(0,a.iw)("openChat",(e=>({...e,activeReactions:{}}))),(0,a.iw)("startActiveReaction",((e,t,n)=>{var a;const{messageId:i,reaction:o}=n,{animationLevel:r}=e.settings.byKey;return r!==s.zy||(null===(a=e.activeReactions[i])||void 0===a?void 0:a.reaction)===o?e:{...e,activeReactions:{...o?e.activeReactions:(0,g.CE)(e.activeReactions,[i]),...o&&{[i]:{reaction:o,messageId:i}}}}})),(0,a.iw)("stopActiveReaction",((e,t,n)=>{var a;const{messageId:s,reaction:i}=n;return(null===(a=e.activeReactions[s])||void 0===a?void 0:a.reaction)!==i?e:{...e,activeReactions:(0,g.CE)(e.activeReactions,[s])}})),(0,a.iw)("setDefaultReaction",(async(e,t,n)=>{const{reaction:s}=n;if(await(0,S.t9)("setDefaultReaction",{reaction:s}))return{...(0,a.Rd)(),appConfig:{...e.appConfig,defaultReaction:s}}})),(0,a.iw)("stopActiveEmojiInteraction",((e,t,n)=>{var a;const{id:s}=n;return{...e,activeEmojiInteractions:null===(a=e.activeEmojiInteractions)||void 0===a?void 0:a.filter((e=>e.id!==s))}})),(0,a.iw)("loadReactors",(async(e,t,n)=>{var s,i,o;const{chatId:l,messageId:d,reaction:u}=n,m=(0,c.Z1)(e,l),h=(0,c.hj)(e,l,d);if(!m||!h)return;const f=null===(s=h.reactors)||void 0===s?void 0:s.nextOffset,p=await(0,S.t9)("fetchMessageReactionsList",{reaction:u,chat:m,messageId:d,offset:f});if(!p)return;e=(0,a.Rd)(),null!==(i=p.users)&&void 0!==i&&i.length&&(e=(0,r.Sh)(e,(0,g.ee)(p.users,"id")));const{nextOffset:v,count:I,reactions:y}=p;return(0,r.cY)(e,l,d,{reactors:{nextOffset:v,count:I,reactions:[...(null===(o=h.reactors)||void 0===o?void 0:o.reactions)||[],...y]}})})),(0,a.iw)("loadMessageReactions",((e,t,n)=>{const{ids:a,chatId:s}=n,i=(0,c.Z1)(e,s);i&&(0,S.t9)("fetchMessageReactions",{ids:a,chat:i})})),(0,a.iw)("sendWatchingEmojiInteraction",((e,t,n)=>{var a;const{chatId:s,emoticon:i,x:o,y:r,startSize:l,isReversed:d,id:u}=n,m=(0,c.Z1)(e,s);if(m&&null!==(a=e.activeEmojiInteractions)&&void 0!==a&&a.some((e=>e.id===u))&&s!==e.currentUserId)return(0,S.t9)("sendWatchingEmojiInteraction",{chat:m,emoticon:i}),{...e,activeEmojiInteractions:e.activeEmojiInteractions.map((t=>t.id===u?{...t,x:ee(e,o),y:r,startSize:l,isReversed:d}:t))}})),(0,a.iw)("loadStatistics",(async(e,t,n)=>{var s;const{chatId:i,isGroup:o}=n,l=(0,c.Z1)(e,i);if(null==l||!l.fullInfo)return;const d=await(0,S.t9)(o?"fetchGroupStatistics":"fetchChannelStatistics",{chat:l});if(d){if(e=(0,a.Rd)(),null!==(s=d.recentTopMessages)&&void 0!==s&&s.length){const t=(0,c.Zw)(e,i);d.recentTopMessages=d.recentTopMessages.map((e=>({...e,...t[e.msgId]})))}return(0,r.ze)(e,i,d)}})),(0,a.iw)("loadStatisticsAsyncGraph",(async(e,t,n)=>{const{chatId:s,token:i,name:o,isPercentage:l}=n,d=(0,c.Z1)(e,s);if(null==d||!d.fullInfo)return;const u=d.fullInfo.statisticsDcId,m=await(0,S.t9)("fetchStatisticsAsyncGraph",{token:i,dcId:u,isPercentage:l});return m?(0,r.yC)((0,a.Rd)(),s,o,m):void 0})),n(8304);var ne=n(8406);function ae(e,t){const n=typeof e;if(n!==typeof t)return!1;if("object"!==n)return e===t;const a=Array.isArray(e);if(a!==Array.isArray(t))return!1;if(a){const n=e,a=t;return n.length===a.length&&n.every(((e,t)=>ae(e,a[t])))}const s=e,i=t;return Object.keys(s).every((e=>ae(s[e],i[e])))}(0,a.iw)("apiUpdate",((e,t,n)=>{switch(n["@type"]){case"updateChat":return n.noTopChatsRequest||(0,c.N)(e,n.id)||t.loadTopChats(),(0,a.R3)((0,r.a4)(e,n.id,n.chat,n.newProfilePhoto)),void(n.chat.id&&(0,ne.Vr)({chatId:n.chat.id,lastReadInboxMessageId:n.chat.lastReadInboxMessageId}));case"updateChatJoin":{const s=(0,c.Ek)(e,n.id);if(!s)return;e=(0,r.B1)(e,s,[n.id]),e=(0,r.a4)(e,n.id,{isNotJoined:!1}),(0,a.R3)(e);const i=(0,c.Z1)(e,n.id);return void(i&&t.requestChatUpdate({chatId:i.id}))}case"updateChatLeave":return(0,r.Dd)(e,n.id);case"updateChatInbox":return(0,r.a4)(e,n.id,n.chat);case"updateChatTypingStatus":{const{id:t,typingStatus:s}=n;return(0,a.R3)((0,r.a4)(e,t,{typingStatus:s})),void setTimeout((()=>{e=(0,a.Rd)();const n=(0,c.Z1)(e,t);n&&s&&n.typingStatus&&n.typingStatus.timestamp===s.timestamp&&(0,a.R3)((0,r.a4)(e,t,{typingStatus:void 0}))}),6e3)}case"newMessage":{const{message:s}=n,{chatId:i,threadId:l,type:d}=(0,c.Bt)(e)||{};if(s.senderId===e.currentUserId&&!s.isFromScheduled)return;const u=(0,c.Z1)(e,n.chatId);if(!u)return;return"thread"===d&&l===o._f&&n.chatId===i?setTimeout((()=>{t.requestChatUpdate({chatId:n.chatId})}),1500):(0,a.R3)((0,r.a4)(e,n.chatId,{unreadCount:u.unreadCount?u.unreadCount+1:1,...n.message.hasUnreadMention&&{unreadMentionsCount:u.unreadMentionsCount?u.unreadMentionsCount+1:1}})),void(0,ne.rh)({chat:u,message:s})}case"updateMessage":{const{message:t}=n,a=(0,c.Z1)(e,n.chatId);if(!a)return;return void((0,d.dT)(t)&&(0,ne.rh)({chat:a,message:t}))}case"updateCommonBoxMessages":case"updateChannelMessages":{const{ids:t,messageUpdate:a}=n;if(!1!==a.hasUnreadMention)return;return t.forEach((t=>{const a="channelId"in n?n.channelId:(0,c.X5)(e,t),s=(0,c.Z1)(e,a);null!=s&&s.unreadMentionsCount&&(e=(0,r.a4)(e,a,{unreadMentionsCount:s.unreadMentionsCount-1}))})),e}case"updateChatFullInfo":{const{fullInfo:t}=n,a=e.chats.byId[n.id];if(!a)return;return(0,r.a4)(e,n.id,{fullInfo:{...a.fullInfo,...t}})}case"updatePinnedChatIds":{const{ids:t,folderId:a}=n,i=a===s.WS?"archived":"active";return{...e,chats:{...e.chats,orderedPinnedIds:{...e.chats.orderedPinnedIds,[i]:t.length?t:void 0}}}}case"updateChatPinned":{const{id:t,isPinned:a}=n,i=(0,c.Ek)(e,t);if(!i)return;const{[i]:o}=e.chats.orderedPinnedIds;let r=o||[];if(a){if(!r.includes(t)){if("active"===i&&r.length>=s.EG){const t=e.chats.listIds.active;r=r.filter((e=>t&&t.includes(e)))}r=[t,...r]}}else r=r.filter((e=>e!==t));return{...e,chats:{...e.chats,orderedPinnedIds:{...e.chats.orderedPinnedIds,[i]:r.length?r:void 0}}}}case"updateChatListType":{const{id:t,folderId:a}=n;return(0,r.Pi)(e,t,a)}case"updateChatFolder":{const{id:t,folder:a}=n,{byId:s,orderedIds:i}=e.chatFolders,o=a?{...s,[t]:a}:(0,g.ei)(s,Object.keys(s).map(Number).filter((e=>e!==t))),r=a?i&&i.includes(t)?i:[...i||[],t]:i?i.filter((e=>e!==t)):void 0;return{...e,chatFolders:{...e.chatFolders,byId:o,orderedIds:r}}}case"updateChatFoldersOrder":{const{orderedIds:t}=n;return{...e,chatFolders:{...e.chatFolders,orderedIds:t}}}case"updateRecommendedChatFolders":{const{folders:t}=n;return{...e,chatFolders:{...e.chatFolders,recommended:t}}}case"updateChatMembers":{var i;const t=e.chats.byId[n.id],{replacedMembers:a,addedMember:s,deletedMemberId:o}=n;if(!t)return;let c=!1,l=null!==(i=t.fullInfo)&&void 0!==i&&i.members?[...t.fullInfo.members]:[];if(a)l=a,c=!0;else if(s)l.length&&l.some((e=>e.userId===s.userId))||(l.push(s),c=!0);else if(l.length&&o){const e=l.findIndex((e=>e.userId===o));e>-1&&(l.slice(e,1),c=!0)}if(c){const a=l.filter((e=>{let{isOwner:t,isAdmin:n}=e;return t||n}));return(0,r.a4)(e,n.id,{membersCount:l.length,fullInfo:{...t.fullInfo,members:l,adminMembers:a}})}return}case"deleteProfilePhotos":{const{chatId:t,ids:a}=n,s=e.chats.byId[t];return null!=s&&s.photos?(0,r.a4)(e,t,{photos:s.photos.filter((e=>!a.includes(e.id)))}):void 0}case"draftMessage":{const{chatId:t,formattedText:a,date:s,replyingToId:i}=n;if(!e.chats.byId[t])return;return e=(0,r.pf)(e,t,o._f,"draft",a),e=(0,r.pf)(e,t,o._f,"replyingToId",i),e=(0,r.a4)(e,t,{draftDate:s})}case"showInvite":{const{data:e}=n;return void t.showDialog({data:e})}case"updatePendingJoinRequests":{const{chatId:s,requestsPending:i,recentRequesterIds:o}=n,c=e.chats.byId[s];if(!c)return;e=(0,r.a4)(e,s,{fullInfo:{...c.fullInfo,requestsPending:i,recentRequesterIds:o}}),(0,a.R3)(e),t.loadChatJoinRequests({chatId:s})}}}));const se=350;function ie(e,t,n,a){let s=arguments.length>4&&void 0!==arguments[4]&&arguments[4];const i=s?(0,c.Tm)(e,t,n):(0,c.hj)(e,t,n);if(i&&a.content){const{photo:e,video:t,sticker:n,document:s}=(0,d.qp)(i);e&&a.content.photo?(a.content.photo.blobUrl=e.blobUrl,a.content.photo.thumbnail=e.thumbnail):t&&a.content.video?a.content.video.blobUrl=t.blobUrl:n&&a.content.sticker?a.content.sticker.isPreloadedGlobally=n.isPreloadedGlobally:s&&a.content.document&&(a.content.document.previewBlobUrl=s.previewBlobUrl)}return s?(0,r.P4)(e,t,n,a):(0,r.cY)(e,t,n,a)}function oe(e,t,n,a){const{chatId:s}=n,{threadInfo:i}=(0,c.Db)(e,s,n)||{};if(!i&&n.replyToMessageId){const i=(0,c.hj)(e,s,n.replyToMessageId);i?e=(0,r.lG)(e,i,s,n.id,a):t.loadMessage({chatId:s,messageId:n.replyToMessageId,threadUpdate:{isDeleting:a,lastMessageId:n.id}})}return e}function re(e,t,n){const{id:a,chatId:s}=n,{threadInfo:i,firstMessageId:l}=(0,c.Db)(e,s,n)||{},u=(0,c.Z1)(e,s),m=(null==u?void 0:u.unreadCount)&&!(0,c.gb)(e,s,o._f);if(e=oe(e,t,n),i&&(!l&&(0,d.CI)(n)||(e=(0,r.xj)(e,s,i.threadId,[a]),(0,c.b9)(e,s,i.threadId)&&(e=(0,r.$S)(e,s,i.threadId,a),l||(e=(0,r.pf)(e,s,i.threadId,"firstMessageId",n.id)))),e=(0,r.pf)(e,s,i.threadId,"threadInfo",{...i,lastMessageId:n.id,messagesCount:i.messagesCount+1})),m)return e;if(e=(0,r.xj)(e,s,o._f,[a]),(0,c.b9)(e,s,o._f)){const t=(0,c.It)(e,s,o._f),n=(0,r.$S)(e,s,o._f,a),i=(0,c.Cb)(n,s,o._f);t&&!i.includes(t)||(e=n)}return e}function ce(e,t,n){var a;let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const{chats:i}=e,o=null===(a=i.byId[t])||void 0===a?void 0:a.lastMessage;return!o||s||o.id===n.id||o.id===n.previousLocalId||n.id>o.id?(0,r.a4)(e,t,{lastMessage:n}):e}function le(e,t){const n=(0,c.Zw)(e,t),a=(0,c.gb)(e,t,o._f);if(!n||!a)return;let s=a.length;for(;s--;){const e=n[a[s]];if(!e.isDeleting)return e}}function de(e,t,n,s){if(e){t.forEach((t=>{const n=le(s=(0,r.cY)(s,e,t,{isDeleting:!0}),e);n&&(s=ce(s,e,n,!0))})),(0,a.R3)(s),n.requestChatUpdate({chatId:e});const i=[];return t.forEach((t=>{const a=(0,c.hj)(s,e,t);if(!a)return;s=oe(s,n,a,!0);const{threadInfo:o}=(0,c.Db)(s,e,a)||{};o&&i.push(o.threadId)})),(0,a.R3)(s),void setTimeout((()=>{(0,a.R3)((0,r.K4)((0,a.Rd)(),e,t)),(0,g.Tw)(i).forEach((t=>{n.requestThreadInfoUpdate({chatId:e,threadId:t})}))}),se)}const i=[];t.forEach((e=>{const t=(0,c.X5)(s,e);if(t){i.push(t);const n=le(s=(0,r.cY)(s,t,e,{isDeleting:!0}),t);n&&(s=ce(s,t,n,!0)),setTimeout((()=>{(0,a.R3)((0,r.K4)((0,a.Rd)(),t,[e]))}),se)}})),(0,a.R3)(s),(0,g.Tw)(i).forEach((e=>{n.requestChatUpdate({chatId:e})}))}(0,a.iw)("apiUpdate",((e,t,n)=>{switch(n["@type"]){case"newMessage":{const{chatId:i,id:l,message:u,shouldForceReply:m}=n;e=re(e=ie(e,i,l,u),t,u),u.threadInfo&&(e=(0,r.Xg)(e,u.threadInfo.chatId,u.threadInfo.threadId,u.threadInfo)),(0,a.R3)(e);const h=(0,c.hj)(e,i,l);if((0,c.KA)(e,i,u)){var s;if(u.isOutgoing&&(null===(s=u.content)||void 0===s||!s.action)){const n=(0,c.Bt)(e);n&&t.focusMessage({chatId:i,threadId:n.threadId,messageId:u.id,noHighlight:!0,isResizingContainer:!0})}const{threadInfo:n}=(0,c.Db)(e,i,u)||{};n&&t.requestThreadInfoUpdate({chatId:i,threadId:n.threadId}),(0,d.CI)(u)||setTimeout((()=>{let e=(0,a.Rd)();m&&(e=(0,r.pf)(e,i,o._f,"replyingToId",l)),(0,a.R3)(ce(e,i,h))}),se)}else(0,a.R3)(ce((0,a.Rd)(),i,h));(0,c.N)(e,i)||t.loadTopChats();break}case"updateStartEmojiInteraction":{var i;const{chatId:t}=(0,c.Bt)(e)||{};if(t!==n.id)return;const s=(0,c.hj)(e,t,n.messageId);if(!s)return;if((0,d.UD)(s)!==n.emoji)return;const o=(0,c.CP)(e,n.emoji);e={...e,activeEmojiInteractions:[...e.activeEmojiInteractions||[],{id:(null===(i=e.activeEmojiInteractions)||void 0===i?void 0:i.length)||0,animatedEffect:o?(0,c.cu)(o):n.emoji,messageId:n.messageId}]},(0,a.R3)(e);break}case"newScheduledMessage":{const{chatId:t,id:s,message:i}=n;e=ie(e,t,s,i,!0);const l=(0,c.qy)(e,t)||[];e=(0,r.pf)(e,t,o._f,"scheduledIds",(0,g.Tw)([...l,s])),(0,a.R3)(e);break}case"updateMessage":{var l,u;const{chatId:s,id:i,message:d}=n;if(!(0,c.hj)(e,s,i))return;e=ie(e,s,i,d);const m=(0,c.hj)(e,s,i);d.threadInfo&&(e=(0,r.Xg)(e,d.threadInfo.chatId,d.threadInfo.threadId,d.threadInfo)),e=ce(e,s,m),(0,a.R3)(e);const h=(0,c.Z1)(e,s);h&&!d.isOutgoing&&(null===(l=h.lastMessage)||void 0===l?void 0:l.id)===d.id&&(0,c.xo)(e,h)&&(0,c.KA)(e,s,d)&&(0,c.b9)(e,s,(null===(u=d.threadInfo)||void 0===u?void 0:u.threadId)||o._f)&&t.focusLastMessage();break}case"updateScheduledMessage":{const{chatId:t,id:s,message:i}=n;if(!(0,c.Tm)(e,t,s))return;e=ie(e,t,s,i,!0);const l=Object.keys((0,c.Fn)(e,t)||{}).map(Number).sort(((e,t)=>t-e));e=(0,r.pf)(e,t,o._f,"scheduledIds",l),(0,a.R3)(e);break}case"updateMessageSendSucceeded":{const{chatId:s,localId:i,message:o}=n;e=re(e,t,o);const l=(0,c.hj)(e,s,i);e=(0,r.K4)(e,s,[i]),o.isScheduled&&(e=(0,r.bV)(e,s,[i])),e=(0,r.cY)(e,s,o.id,{...l,...o,previousLocalId:i});const d=(0,c.hj)(e,s,o.id);e=ce(e,s,d);const u=(0,c.Db)(e,s,o);null!=u&&u.threadInfo&&(t.markMessageListRead({maxId:o.id}),e=(0,r.pf)(e,s,u.threadInfo.threadId,"threadInfo",{...u.threadInfo,lastMessageId:o.id,lastReadInboxMessageId:o.id})),(0,a.R3)(e);break}case"updateScheduledMessageSendSucceeded":{const{chatId:t,localId:s,message:i}=n,l=(0,c.qy)(e,t)||[];e=(0,r.pf)(e,t,o._f,"scheduledIds",[...l,i.id]);const d=(0,c.Tm)(e,t,s);e=(0,r.bV)(e,t,[s]),e=(0,r.P4)(e,t,i.id,{...d,...i,previousLocalId:s}),(0,a.R3)(e);break}case"updatePinnedIds":{const{chatId:t,isPinned:s,messageIds:i}=n,l=(0,c.KB)(e,t)||[],d=s?[...l,...i].sort(((e,t)=>t-e)):l.filter((e=>!i.includes(e)));(0,a.R3)((0,r.pf)(e,t,o._f,"pinnedIds",d));break}case"updateThreadInfo":{const{chatId:t,threadId:s,threadInfo:i,firstMessageId:o}=n,l={...(0,c.tZ)(e,t,s),...i};if(!l.threadId)return;e=(0,r.Xg)(e,t,s,l),o&&(e=(0,r.pf)(e,t,s,"firstMessageId",o)),(0,a.R3)(e);break}case"resetMessages":{const{id:s}=n,i=(0,c.Zw)(e,s);i&&!(0,d.YC)(s)&&(e=(0,r.K4)(e,s,Object.keys(i).map(Number)),(0,a.R3)(e),t.loadFullChat({chatId:s,force:!0}));break}case"deleteMessages":{const{ids:a,chatId:s}=n;de(s,a,t,e);break}case"deleteScheduledMessages":{const{ids:t,chatId:s}=n;!function(e,t,n,s){e&&(t.forEach((t=>{s=(0,r.P4)(s,e,t,{isDeleting:!0})})),(0,a.R3)(s),setTimeout((()=>{s=(0,r.bV)((0,a.Rd)(),e,t);const n=(0,c.Fn)(s,e);s=(0,r.pf)(s,e,o._f,"scheduledIds",Object.keys(n||{}).map(Number)),(0,a.R3)(s)}),se))}(s,t,0,e);break}case"deleteHistory":{const{chatId:a}=n,s=e.messages.byChatId[a];s?de(a,Object.keys(s.byId).map(Number),t,e):t.requestChatUpdate({chatId:a});break}case"updateCommonBoxMessages":{const{ids:t,messageUpdate:s}=n;t.forEach((t=>{const n=(0,c.X5)(e,t);n&&(e=(0,r.cY)(e,n,t,s))})),(0,a.R3)(e);break}case"updateChannelMessages":{const{channelId:t,ids:s,messageUpdate:i}=n;s.forEach((n=>{e=(0,r.cY)(e,t,n,i)})),(0,a.R3)(e);break}case"updateMessagePoll":{const{pollId:t,pollUpdate:s}=n,i=(0,c.ZB)(e,t);if(null!=i&&i.content.poll){const t={...i.content.poll,...s},{results:n}=t.results||{};if(n&&!n.some((e=>e.isChosen))){const{results:e}=i.content.poll.results,a=e&&e.filter((e=>e.isChosen));a&&a.forEach((e=>{const a=n.findIndex((t=>t.option===e.option));a>=0&&(t.results.results[a].isChosen=!0)}))}(0,a.R3)((0,r.cY)(e,i.chatId,i.id,{content:{...i.content,poll:t}}))}break}case"updateMessagePollVote":{const{pollId:t,userId:s,options:i}=n,o=(0,c.ZB)(e,t);if(!o||!o.content.poll||!o.content.poll.results)break;const{poll:l}=o.content,{recentVoterIds:d,totalVoters:u,results:m}=l.results,h=d?[...d]:[],g=u?u+1:1,f=m?[...m]:[];h.push(s),i.forEach((t=>{const n=f.find((e=>e.option===t)),a=f.findIndex((e=>e.option===t)),i=n?{...n}:{option:t,votersCount:0};i.votersCount+=1,s===e.currentUserId&&(i.isChosen=!0),a?f[a]=i:f.push(i)})),(0,a.R3)((0,r.cY)(e,o.chatId,o.id,{content:{...o.content,poll:{...l,results:{...l.results,recentVoterIds:h,totalVoters:g,results:f}}}}));break}case"updateServiceNotification":{const{message:a}=n;(0,c.UW)(e)&&t.createServiceNotification({message:a});break}case"updateMessageReactions":{const{chatId:t,id:s,reactions:i}=n,o=(0,c.hj)(e,t,s),l=(0,c.Z1)(e,n.chatId),u=null==o?void 0:o.reactions;if(u&&ae(i,u))return;const m=(0,d.lb)(u,i,e.currentUserId);if(e=(0,r.cY)(e,t,s,{reactions:n.reactions}),m){const n=(0,c.hj)(e,t,s);if(!l||!n)return;(0,ne.rh)({chat:l,message:n,isReaction:!0})}(0,a.R3)(e);break}}}));const ue=(0,E.P2)((function(){const e=(0,a.Rd)();(0,a.R3)((0,r.ps)(e,{...e.users.statusesById,...me})),me={}}),3e3,!0);let me={};(0,a.iw)("apiUpdate",((e,t,n)=>{switch(n["@type"]){case"deleteContact":return(0,r.GK)(e,n.id);case"updateUser":return(0,r.Nq)(e,n.id,n.user);case"updateUserStatus":return a=n.userId,s=n.status,me[a]=s,void ue();case"updateUserFullInfo":{const{id:t,fullInfo:a}=n,s=e.users.byId[t];if(!s)return;return(0,r.Nq)(e,t,{fullInfo:{...s.fullInfo,...a}})}}var a,s})),(0,a.iw)("apiUpdate",((e,t,n)=>{if("updateStickerSet"===n["@type"])return(0,r.Rg)(e,n.id,n.stickerSet)})),(0,a.iw)("apiUpdate",((e,t,n)=>{switch(n["@type"]){case"updatePeerBlocked":return n.isBlocked?(0,r.O4)((0,a.Rd)(),n.id):(0,r.rB)((0,a.Rd)(),n.id);case"updateResetContactList":(0,a.R3)({...(0,a.Rd)(),contactList:{userIds:[]}});break;case"updateFavoriteStickers":t.loadFavoriteStickers();break;case"updatePrivacy":e.settings.privacy[n.key]=n.rules;break;case"updatePaymentVerificationNeeded":e=(0,r.fS)((0,a.Rd)(),n.url),e=(0,r.Q$)(e,m.KB.ConfirmPayment),(0,a.R3)(e)}})),(0,a.iw)("apiUpdate",((e,t,n)=>{switch(n["@type"]){case"updateNotifySettings":return(0,r.HN)(e,n.peerType,n.isSilent,n.shouldShowPreviews);case"updateNotifyExceptions":{const{chatId:t,isMuted:s,isSilent:i,shouldShowPreviews:o}=n;e.chats.byId[t]&&(e=(0,r.a4)(e,t,{isMuted:s})),(0,a.R3)((0,r.aK)(e,t,{isMuted:s,isSilent:i,shouldShowPreviews:o}));break}}})),(0,a.iw)("apiUpdate",((e,t,n)=>{switch(n["@type"]){case"updateTwoFaStateWaitCode":return{...e,twoFaSettings:{...e.twoFaSettings,isLoading:!1,waitingEmailCodeLength:n.length}};case"updateTwoFaError":return{...e,twoFaSettings:{...e.twoFaSettings,error:n.message}}}}));var he=n(8958);(0,a.iw)("apiUpdate",((e,t,n)=>{switch(n["@type"]){case"updateGroupCall":return"discarded"===n.call.connectionState?e.groupCalls.activeGroupCallId?void t.leaveGroupCall({shouldRemove:!0}):(0,he.dc)(e,n.call.id):(0,he.AH)(e,n.call.id,(0,g.CE)(n.call,["connectionState"]),void 0,n.call.participantsCount);case"updateGroupCallChatId":{const t=(0,c.Z1)(e,n.chatId);return t&&(e=(0,r.a4)(e,n.chatId,{fullInfo:{...t.fullInfo,groupCallId:n.call.id}})),e}case"updateGroupCallParticipants":{const{groupCallId:t,participants:s,nextOffset:i}=n,{currentUserId:o}=e;return e=(0,a.Rd)(),s.forEach((n=>{n.id&&(e=(0,he.B6)(e,t,n.id,n,Boolean(i)||o===n.id))})),i&&(e=(0,he.AH)(e,t,{nextOffset:i})),e}}})),(0,a.iw)("apiUpdate",((e,t,n)=>{if("updatePaymentStateCompleted"===n["@type"])return(0,r.bp)(e)}));var ge=n(8674),fe=n(6752),pe=n(1279),ve=n(3551),Ie=n(3227),ye=n(1212),we=n(5332);function Ze(e){(0,i.d4)((()=>(0,E.Gq)(e)),[e])}var Pe=n(9290);const Ce=document.querySelector('meta[name="viewport"]'),be=(null==Ce?void 0:Ce.getAttribute("content"))||"",Se="width=device-width, initial-scale=1, shrink-to-fit=no, viewport-fit=cover";function Ee(e){e.preventDefault()}var Me=n(6590),ke=n(4851),Re=n(2155),Ne=n(1334),Te=n(7358);const Be=(0,i.X$)((e=>{let{isForAppBadge:t}=e;(0,Ne.yi)();const n=(0,D.xW)();if((0,i.d4)((()=>{t&&(0,Te.w)(n)}),[t,n]),!t&&n)return i.ZP.createElement("div",{className:"unread-count active"},(0,Re.bi)(n))}));var Ae=n(3989),xe=n(7529),Le=n(3455),Oe=n(706),Ue=n(2255),Fe=n(9107),De=n(7370),$e=n(7926),qe=n(1622);let je;function Ge(e,t,n,a,s,o){let r,c,l;return r=function(){const[e,t]=(0,i.eJ)(window.navigator.onLine);return(0,i.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}()&&"connectionStateConnecting"!==t?n?je.syncing:je.online:je.waitingForNetwork,c=r===je.online||o?"none":a?"middleHeader":s?"minimized":"overlay",r===je.waitingForNetwork?l=e("WaitingForNetwork"):r===je.syncing&&(l=e("Updating")),"middleHeader"===c&&(l=l.toLowerCase().replace(/\.+$/,"")),{connectionStatus:r,connectionStatusPosition:c,connectionStatusText:l}}!function(e){e[e.waitingForNetwork=0]="waitingForNetwork",e[e.syncing=1]="syncing",e[e.online=2]="online"}(je||(je={}));var He=n(3106),_e=n(8964),ze=n(231),Ve=n(9589),Xe=n(9187),Ke=n(3321),We=n(126),Ye=n(9204);const Je=(0,i.X$)((e=>{let{connectionStatus:t,connectionStatusText:n,onClick:a}=e;const s=(0,Fe.Z)();return i.ZP.createElement("div",{id:"ConnectionStatusOverlay",dir:s.isRtl?"rtl":void 0,onClick:a},i.ZP.createElement(Ye.Z,{color:"black"}),i.ZP.createElement("div",{className:"state-text"},i.ZP.createElement(Ue.Z,{activeKey:t,name:"slide-fade"},n)),i.ZP.createElement(ze.Z,{round:!0,size:"tiny",color:"translucent-black"},i.ZP.createElement("span",{className:"icon-close"})))})),Qe=[0,1,2],et=(0,i.X$)((0,a.c$)((e=>{const{query:t,fetchingStatus:n,chatId:a,date:s}=e.globalSearch,{currentUserId:i,connectionState:o,isSyncing:r}=e,{byId:l}=e.chats,{isConnectionStatusMinimized:d,animationLevel:u}=e.settings.byKey;return{searchQuery:t,isLoading:!!n&&Boolean(n.chats||n.messages),currentUserId:i,chatsById:l,globalSearchChatId:a,searchDate:s,theme:(0,c.Pu)(e),animationLevel:u,connectionState:o,isSyncing:r,isMessageListOpen:Boolean((0,c.Bt)(e)),isConnectionStatusMinimized:d,areChatsLoaded:Boolean(e.chats.listIds.active)}}))((e=>{let{content:t,contactsFilter:n,onSearchQuery:o,onSelectSettings:r,onSelectContacts:c,onSelectArchived:l,onReset:u,searchQuery:g,isLoading:f,shouldSkipTransition:p,currentUserId:v,globalSearchChatId:I,searchDate:y,theme:w,animationLevel:Z,chatsById:P,connectionState:C,isSyncing:b,isMessageListOpen:S,isConnectionStatusMinimized:E,areChatsLoaded:M}=e;const{openChat:k,openTipsChat:R,setGlobalSearchDate:N,setSettingOption:T,setGlobalSearchChatId:B}=(0,a.Sv)(),A=(0,Fe.Z)(),x=t===m.du.ChatList,O=(0,i.Ye)((()=>y?(0,L.xH)(new Date(1e3*y)):void 0),[y]),U=(0,i.Ye)((()=>x&&P?Object.values(P).reduce(((e,t)=>(0,d.pE)(t)&&t.unreadCount?e+1:e),0):0),[x,P]),{connectionStatus:F,connectionStatusText:D,connectionStatusPosition:$}=Ge(A,C,b,S,E,!M),q="web.telegram.org"===window.location.hostname,j=(0,i.Ye)((()=>e=>{let{onTrigger:t,isOpen:n}=e;return i.ZP.createElement(ze.Z,{round:!0,ripple:x&&!h.wB,size:"smaller",color:"translucent",className:n?"active":"",onClick:x?t:()=>u(),ariaLabel:x?A("AccDescrOpenMenu2"):"Return to chat list"},i.ZP.createElement("div",{className:(0,fe.Z)("animated-menu-icon",!x&&"state-back",p&&"no-animation")}))}),[x,A,u,p]),G=(0,i.I4)((()=>{g||o("")}),[g,o]),H=(0,i.I4)((()=>{T({isConnectionStatusMinimized:!E})}),[E,T]),_=(0,i.I4)((()=>{k({id:v,shouldReplaceHistory:!0})}),[v,k]),z=(0,i.I4)((e=>{e.stopPropagation();const t="light"===w?"dark":"light";T({theme:t}),T({shouldUseSystemTheme:!1}),(0,De.Z)(t,Z===s.zy)}),[Z,T,w]),V=(0,i.I4)((e=>{e.stopPropagation();const t=0===Z?2:0;Qe.forEach(((e,n)=>{document.body.classList.toggle(`animation-level-${n}`,t===n)})),T({animationLevel:t})}),[Z,T]),X=Boolean(I)||t===m.du.GlobalSearch||t===m.du.Contacts,K=t===m.du.Contacts?A("SearchFriends"):A("Search");return i.ZP.createElement("div",{className:"LeftMainHeader"},i.ZP.createElement("div",{id:"LeftMainHeader",className:"left-header"},i.ZP.createElement(He.Z,{trigger:j,footer:`${s.iC} ${s.eM?"master":s.Ji}`},i.ZP.createElement(_e.Z,{icon:"saved-messages",onClick:_},A("SavedMessages")),i.ZP.createElement(_e.Z,{icon:"archive",onClick:l},i.ZP.createElement("span",{className:"menu-item-name"},A("ArchivedChats")),U>0&&i.ZP.createElement("div",{className:"archived-badge"},U)),i.ZP.createElement(_e.Z,{icon:"user",onClick:c},A("Contacts")),i.ZP.createElement(_e.Z,{icon:"settings",onClick:r},A("Settings")),i.ZP.createElement(_e.Z,{icon:"darkmode",onClick:z},i.ZP.createElement("span",{className:"menu-item-name"},A("lng_menu_night_mode")),i.ZP.createElement(Ke.Z,{id:"darkmode",label:A("dark"===w?"lng_settings_disable_night_theme":"lng_settings_enable_night_theme"),checked:"dark"===w,noAnimation:!0})),i.ZP.createElement(_e.Z,{icon:"animations",onClick:V},i.ZP.createElement("span",{className:"menu-item-name capitalize"},A("Appearance.Animations").toLowerCase()),i.ZP.createElement(Ke.Z,{id:"animations",label:"Toggle Animations",checked:Z>0})),i.ZP.createElement(_e.Z,{icon:"help",onClick:()=>{R({langCode:A.code})}},A("TelegramFeatures")),i.ZP.createElement(_e.Z,{icon:"bug",href:s.mU},"Report Bug"),q&&i.ZP.createElement(i.ZP.Fragment,null,i.ZP.createElement(_e.Z,{icon:"char-K",href:"https://web.telegram.org/k/",onClick:()=>{(0,$e.L)("K"),(0,qe.W8)(),(0,Me.Wv)()}},"Switch to K Version"),i.ZP.createElement(_e.Z,{icon:"char-W",href:"https://web.telegram.org/?legacy=1",onClick:Me.Wv},"Switch to Old Version"))),i.ZP.createElement(Ve.Z,{inputId:"telegram-search-input",parentContainerClassName:"LeftSearch",className:I||y?"with-picker-item":"",value:n||g,focused:X,isLoading:f||"minimized"===$,spinnerColor:"minimized"===$?"yellow":void 0,spinnerBackgroundColor:"minimized"===$&&"light"===w?"light":void 0,placeholder:K,autoComplete:"off",canClose:Boolean(I||y),onChange:o,onReset:u,onFocus:G,onSpinnerClick:"minimized"===$?H:void 0},O&&i.ZP.createElement(Xe.Z,{icon:"calendar",title:O,canClose:!0,isMinimized:Boolean(I),className:"search-date",onClick:N,clickArg:{date:void 0}}),I&&i.ZP.createElement(Xe.Z,{chatOrUserId:I,onClick:B,canClose:!0,clickArg:{id:void 0}})),i.ZP.createElement(We.Z,{isOpen:"overlay"===$,isCustom:!0,className:"connection-state-wrapper"},i.ZP.createElement(Je,{connectionStatus:F,connectionStatusText:D,onClick:H}))))})));var tt=n(1174),nt=n(3133),at=n(1080);const st=(0,i.X$)((0,a.c$)((e=>{const{chatFolders:{byId:t,orderedIds:n,activeChatFolder:a},currentUserId:s,lastSyncTime:i,shouldSkipHistoryAnimations:o}=e;return{chatFoldersById:t,orderedFolderIds:n,activeChatFolder:a,currentUserId:s,lastSyncTime:i,shouldSkipHistoryAnimations:o}}))((e=>{let{foldersDispatch:t,onScreenSelect:n,chatFoldersById:o,orderedFolderIds:r,activeChatFolder:c,currentUserId:l,lastSyncTime:d,shouldSkipHistoryAnimations:u}=e;const{loadChatFolders:m,setActiveChatFolder:g,openChat:f}=(0,a.Sv)(),p=(0,i.sO)(null),v=(0,Fe.Z)();(0,i.d4)((()=>{d&&m()}),[d,m]);const I=(0,i.Ye)((()=>r?r.map((e=>o[e]||{})).filter(Boolean):void 0),[o,r]),y=(0,Ne.yi)(),w=(0,i.Ye)((()=>{if(I&&I.length)return[{id:s.Nf,title:"en"===v.code?"All":v("FilterAllChats")},...I.map((e=>{var t,n;let{id:a,title:s}=e;return{id:a,title:s,badgeCount:null===(t=y[a])||void 0===t?void 0:t.chatsCount,isBadgeActive:Boolean(null===(n=y[a])||void 0===n?void 0:n.notificationsCount)}}))]}),[I,y,v]),Z=(0,i.I4)((e=>{g(e,{forceOnHeavyAnimation:!0})}),[g]);(0,i.d4)((()=>{w&&w.length&&c>=w.length&&g(0)}),[c,w,g]),(0,i.d4)((()=>{if(p.current&&h.$b&&w&&w.length)return(0,tt.sf)(p.current,{selectorToPreventScroll:".chat-list",onSwipe:(e,t)=>t===tt.eM.Left?(g(Math.min(c+1,w.length-1),{forceOnHeavyAnimation:!0}),!0):t===tt.eM.Right&&(g(Math.max(0,c-1),{forceOnHeavyAnimation:!0}),!0)})}),[c,w,g]);const P=(0,i.sO)();P.current=0!==c,(0,i.d4)((()=>P.current?(0,Ae.Z)((()=>{P.current&&g(0)})):void 0),[c,g]),(0,Me.ZP)(0!==c,(()=>g(0,{forceOnHeavyAnimation:!0}))),(0,i.d4)((()=>{const e=e=>{if(e.ctrlKey&&e.shiftKey&&e.code.startsWith("Digit")&&w){const[,t]=e.code.match(/Digit(\d)/)||[];if(!t)return;if("0"===t)return void f({id:l,shouldReplaceHistory:!0});const n=Number(t)-1;if(n>w.length-1)return;g(n,{forceOnHeavyAnimation:!0}),e.preventDefault()}};return document.addEventListener("keydown",e,!0),()=>{document.removeEventListener("keydown",e,!0)}}));const{shouldRender:C,transitionClassNames:b}=(0,ye.Z)(!r,void 0,!0);function S(e){const a=Object.values(o).find((e=>{let{id:t}=e;return t===w[c].id}));return a&&0!==c?i.ZP.createElement(at.Z,{folderType:"folder",folderId:a.id,isActive:e,lastSyncTime:d,onScreenSelect:n,foldersDispatch:t}):i.ZP.createElement(at.Z,{folderType:"all",isActive:e,lastSyncTime:d,foldersDispatch:t,onScreenSelect:n})}return i.ZP.createElement("div",{className:"ChatFolders"},null!=w&&w.length?i.ZP.createElement(nt.Z,{tabs:w,activeTab:c,onSwitchTab:Z}):C?i.ZP.createElement("div",{className:(0,fe.Z)("tabs-placeholder",b)}):void 0,i.ZP.createElement(Ue.Z,{ref:p,name:u?"none":v.isRtl?"slide-optimized-rtl":"slide-optimized",activeKey:c,renderCount:w?w.length:void 0},S))})));var it=n(9203),ot=n(8778),rt=n(4288);const ct=(0,i.X$)((e=>{const t=(0,ot.Z)(it.gl.Extra,"LeftSearch");return t?i.ZP.createElement(t,e):i.ZP.createElement(rt.Z,null)})),lt=(0,i.X$)((e=>{const t=(0,ot.Z)(it.gl.Extra,"ContactList");return t?i.ZP.createElement(t,e):i.ZP.createElement(rt.Z,null)}));var dt=n(2328);const ut=(0,i.X$)((e=>{let{isShown:t,onNewPrivateChat:n,onNewChannel:a,onNewGroup:s}=e;const[o,r]=(0,i.eJ)(!1);(0,i.d4)((()=>{t||r(!1)}),[t]);const c=(0,Fe.Z)(),l=(0,fe.Z)("NewChatButton",t&&"revealed",o&&"menu-is-open");return i.ZP.createElement("div",{className:l},i.ZP.createElement(ze.Z,{round:!0,color:"primary",className:o?"active":"",onClick:()=>{r(!o)},ariaLabel:c(o?"Close":"NewMessageTitle"),tabIndex:-1},i.ZP.createElement("i",{className:"icon-new-chat-filled"}),i.ZP.createElement("i",{className:"icon-close"})),i.ZP.createElement(dt.Z,{isOpen:o,positionX:"right",positionY:"bottom",autoClose:!0,onClose:()=>{r(!1)}},i.ZP.createElement(_e.Z,{icon:"channel",onClick:a},c("NewChannel")),i.ZP.createElement(_e.Z,{icon:"group",onClick:s},c("NewGroup")),i.ZP.createElement(_e.Z,{icon:"user",onClick:n},c("NewMessageTitle"))))})),mt=Object.keys(m.du).length/2;let ht;const gt=(0,i.X$)((e=>{let{content:t,searchQuery:n,searchDate:a,contactsFilter:s,shouldSkipTransition:o,foldersDispatch:r,onSearchQuery:c,onContentChange:l,onScreenSelect:d,onReset:u}=e;const[g,f]=(0,i.eJ)(h.$b),p=(0,i.sO)(!1),v=(0,i.I4)((()=>{l(m.du.Settings)}),[l]),I=(0,i.I4)((()=>{l(m.du.Contacts)}),[l]),y=(0,i.I4)((()=>{l(m.du.NewChannelStep1)}),[l]),w=(0,i.I4)((()=>{l(m.du.NewGroupStep1)}),[l]),Z=(0,i.I4)((()=>{l(m.du.Archived)}),[l]),P=(0,i.I4)((()=>{t===m.du.ChatList&&(p.current=!0,f(!0))}),[t]),C=(0,i.I4)((()=>{p.current=!1,ht&&(clearTimeout(ht),ht=void 0),ht=window.setTimeout((()=>{p.current||f(!1)}),250)}),[]);(0,i.d4)((()=>{let e;return t!==m.du.ChatList?e=window.setTimeout((()=>{f(!1)}),250):(p.current||h.$b)&&f(!0),()=>{e&&(clearTimeout(e),e=void 0)}}),[t]);const[b,S,E]=function(){const[e,t]=(0,Oe.Z)(!1);(0,i.d4)((()=>{const e=window.setTimeout(t,2592e5);return()=>{clearTimeout(e)}}),[t]);const{shouldRender:n,transitionClassNames:a}=(0,ye.Z)(e);return[n,a,()=>{window.location.reload()}]}(),M=(0,Fe.Z)();return i.ZP.createElement("div",{id:"LeftColumn-main",onMouseEnter:h.$b?void 0:P,onMouseLeave:h.$b?void 0:C},i.ZP.createElement(et,{content:t,contactsFilter:s,onSearchQuery:c,onSelectSettings:v,onSelectContacts:I,onSelectArchived:Z,onReset:u,shouldSkipTransition:o}),i.ZP.createElement(Ue.Z,{name:o?"none":"zoom-fade",renderCount:mt,activeKey:t,shouldCleanup:!0,cleanupExceptionKey:m.du.ChatList},(e=>{switch(t){case m.du.ChatList:return i.ZP.createElement(st,{onScreenSelect:d,foldersDispatch:r});case m.du.GlobalSearch:return i.ZP.createElement(ct,{searchQuery:n,searchDate:a,isActive:e,onReset:u});case m.du.Contacts:return i.ZP.createElement(lt,{filter:s,isActive:e,onReset:u});default:return}})),b&&i.ZP.createElement(ze.Z,{fluid:!0,pill:!0,className:(0,fe.Z)("btn-update",S),onClick:E},M("lng_update_telegram")),i.ZP.createElement(ut,{isShown:g,onNewPrivateChat:I,onNewChannel:y,onNewGroup:w}))})),ft=(0,i.X$)((e=>{const t=(0,ot.Z)(it.gl.Extra,"Settings");return t?i.ZP.createElement(t,e):i.ZP.createElement(rt.Z,null)})),pt=(0,i.X$)((e=>{const t=(0,ot.Z)(it.gl.Extra,"NewChat");return t?i.ZP.createElement(t,e):i.ZP.createElement(rt.Z,null)})),vt=(0,i.X$)((e=>{const t=(0,ot.Z)(it.gl.Extra,"ArchivedChats");return t?i.ZP.createElement(t,e):i.ZP.createElement(rt.Z,null)}));var It;!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"}(It||(It={}));const yt=Object.keys(It).length/2,wt=(0,i.X$)((0,a.c$)((e=>{const{globalSearch:{query:t,date:n},chatFolders:{activeChatFolder:a},shouldSkipHistoryAnimations:s,leftColumnWidth:i}=e;return{searchQuery:t,searchDate:n,activeChatFolder:a,shouldSkipHistoryAnimations:s,leftColumnWidth:i}}))((e=>{let{searchQuery:t,searchDate:n,activeChatFolder:s,shouldSkipHistoryAnimations:o,leftColumnWidth:r}=e;const{setGlobalSearchQuery:c,setGlobalSearchChatId:l,resetChatCreation:d,setGlobalSearchDate:u,loadPasswordInfo:g,clearTwoFaError:f,setLeftColumnWidth:p,resetLeftColumnWidth:v}=(0,a.Sv)(),I=(0,i.sO)(null),[y,w]=(0,i.eJ)(m.du.ChatList),[Z,P]=(0,i.eJ)(m.MT.Main),[C,b]=(0,i.eJ)(""),[S,E]=(0,Le.ZP)(),[M,k]=(0,i.eJ)(0);let R=It.Main;switch(y){case m.du.Archived:R=It.Archived;break;case m.du.Settings:R=It.Settings;break;case m.du.NewChannelStep1:case m.du.NewChannelStep2:R=It.NewChannel;break;case m.du.NewGroupStep1:case m.du.NewGroupStep2:R=It.NewGroup}const N=(0,i.I4)((e=>{if(y!==m.du.NewGroupStep2||e)if(y!==m.du.NewChannelStep2||e){if(y===m.du.NewGroupStep1){const e=document.getElementById("new-group-picker-search");e&&e.blur()}if(y===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:case m.MT.QuickReaction: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 w(m.du.ChatList),void P(m.MT.Main)}y!==m.du.ChatList||0!==s?(w(m.du.ChatList),b(""),c({query:""}),u({date:void 0}),l({id:void 0}),d(),setTimeout((()=>{k(Date.now())}),250)):w(m.du.GlobalSearch)}else w(m.du.NewChannelStep1);else w(m.du.NewGroupStep1)}),[y,s,Z,c,u,l,d]),T=(0,i.I4)((e=>{y!==m.du.Contacts?(w(m.du.GlobalSearch),e!==t&&c({query:e})):b(e)}),[y,t,c]);(0,i.d4)((()=>y!==m.du.ChatList||0===s?(0,Ae.Z)((()=>N())):void 0),[s,y,N]),(0,i.d4)((()=>{if(y!==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,xe.Z)(e)&&(e.preventDefault(),w(m.du.GlobalSearch))}}),[y]),(0,i.d4)((()=>{f(),Z===m.MT.Privacy&&g()}),[f,g,Z]);const{initResize:B,resetResize:A,handleMouseUp:x}=function(e,t,n,a){const[s,o,r]=(0,Oe.Z)(),[c,l]=(0,i.eJ)(),[d,u]=(0,i.eJ)();function m(){document.body.classList.remove("cursor-ew-resize")}return(0,i.d4)((()=>{e.current&&a&&(e.current.style.width=`${a}px`)}),[e,a]),(0,i.d4)((()=>{if(!s)return;const n=t=>{const n=Math.ceil(d+t.clientX-c);e.current.style.width=`${n}px`};function a(){i(),t(e.current.offsetWidth)}function i(){m(),document.removeEventListener("mousemove",n,!1),document.removeEventListener("mouseup",a,!1),document.removeEventListener("blur",a,!1),r()}return document.addEventListener("mousemove",n,!1),document.addEventListener("mouseup",a,!1),document.addEventListener("blur",a,!1),i}),[d,c,e,t,s,r]),{initResize:function(t){t.preventDefault(),document.body.classList.add("cursor-ew-resize"),l(t.clientX),u(e.current.offsetWidth),o()},resetResize:function(t){t.preventDefault(),e.current.style.width="",n()},handleMouseUp:m}}(I,p,v,r),L=e=>{w(m.du.Settings),P(e)};return i.ZP.createElement("div",{id:"LeftColumn",ref:I},i.ZP.createElement(Ue.Z,{name:o?"none":h.s0,renderCount:yt,activeKey:R,shouldCleanup:!0,cleanupExceptionKey:It.Main},(e=>{switch(R){case It.Archived:return i.ZP.createElement(vt,{isActive:e,onReset:N,onContentChange:w});case It.Settings:return i.ZP.createElement(ft,{isActive:e,currentScreen:Z,foldersState:S,foldersDispatch:E,onScreenSelect:L,onReset:N,shouldSkipTransition:o});case It.NewChannel:return i.ZP.createElement(pt,{key:M,isActive:e,isChannel:!0,content:y,onContentChange:w,onReset:N});case It.NewGroup:return i.ZP.createElement(pt,{key:M,isActive:e,content:y,onContentChange:w,onReset:N});default:return i.ZP.createElement(gt,{content:y,searchQuery:t,searchDate:n,contactsFilter:C,foldersDispatch:E,onContentChange:w,onSearchQuery:T,onScreenSelect:L,onReset:N,shouldSkipTransition:o})}})),i.ZP.createElement("div",{className:"resize-handle",onMouseDown:B,onMouseUp:x,onDoubleClick:A}))})));var Zt=n(2420),Pt=n(5780),Ct=n(9524),bt=n(1394);const St=()=>{const[e,t]=(0,i.eJ)(Q.Z.get());return(0,i.d4)((()=>{const e=(0,E.P2)((()=>{t(Q.Z.get())}),250,!1);return window.addEventListener("resize",e),()=>{window.removeEventListener("resize",e)}}),[]),e};var Et=n(2678),Mt=n(7204),kt=n(5326),Rt=n(3570),Nt=n(5790),Tt=n(8360),Bt=n(6058),At=n(8799);const xt=(0,i.X$)((e=>{const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"HeaderMenuContainer",!t);return n?i.ZP.createElement(n,e):void 0})),Lt=(0,i.X$)((0,a.c$)(((e,t)=>{var n,a,s;let{chatId:i,threadId:r,messageListType:l}=t;const u=(0,c.Z1)(e,i),m=Boolean(u&&(0,d.eA)(u));if(!u||u.isRestricted||(0,c.CA)(e))return{noMenu:!0};const g=(0,c.IK)(e,i),f=(0,c.FM)(e,i),p="thread"===l&&r===o._f,v="thread"===l&&r!==o._f,I=(0,c.Jf)(e),y=Boolean(g&&(0,c.s4)(e,g.id)),w=!y&&Boolean((0,c.pk)(e,i)),Z=Boolean(p&&(m||(0,d.ZV)(u))&&u.isNotJoined),P=p||v,C=h.Bi&&(0,d.YC)(u.id)&&!f&&!g,b=p&&!f&&!Z,S=p&&!Z,E=h.Bi&&u.isCallActive,M=h.Bi&&!u.isCallActive&&((null===(n=u.adminRights)||void 0===n?void 0:n.manageCall)||u.isCreator&&(0,d.G9)(u));return{noMenu:!1,isChannel:m,isRightColumnShown:I,canStartBot:w,canRestartBot:y,canSubscribe:Z,canSearch:P,canCall:C,canMute:b,canViewStatistics:null===(a=u.fullInfo)||void 0===a?void 0:a.canViewStatistics,canLeave:S,canEnterVoiceChat:E,canCreateVoiceChat:M,pendingJoinRequests:null===(s=u.fullInfo)||void 0===s?void 0:s.requestsPending}}))((e=>{let{chatId:t,threadId:n,noMenu:s,isChannel:o,canStartBot:r,canRestartBot:c,canSubscribe:l,canSearch:d,canCall:u,canMute:g,canViewStatistics:f,canLeave:p,canEnterVoiceChat:v,canCreateVoiceChat:I,pendingJoinRequests:y,isRightColumnShown:w,canExpandActions:Z}=e;const{joinChannel:P,sendBotCommand:C,openLocalTextSearch:b,restartBot:S,openCallFallbackConfirm:E,requestNextManagementScreen:M}=(0,a.Sv)(),k=(0,i.sO)(null),[R,N]=(0,i.eJ)(!1),[T,B]=(0,i.eJ)(void 0),A=(0,i.I4)((()=>{N(!0);const e=k.current.getBoundingClientRect();B({x:e.right,y:e.bottom})}),[]),x=(0,i.I4)((()=>{N(!1)}),[]),L=(0,i.I4)((()=>{B(void 0)}),[]),O=(0,i.I4)((()=>{P({chatId:t})}),[P,t]),U=(0,i.I4)((()=>{C({command:"/start"})}),[C]),F=(0,i.I4)((()=>{S({chatId:t})}),[t,S]),D=(0,i.I4)((()=>{M({screen:m.u1.JoinRequests})}),[M]),$=(0,i.I4)((()=>{b(),h.wB?document.querySelector("#MobileSearch input").focus():setTimeout((()=>{const e=document.querySelector(".RightHeader .SearchInput input");e&&e.focus()}),400)}),[b]);(0,i.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,xe.Z)(e)&&(e.preventDefault(),$())}}),[d,$]);const q=(0,Fe.Z)();return i.ZP.createElement("div",{className:"HeaderActions"},!h.wB&&i.ZP.createElement(i.ZP.Fragment,null,Z&&l&&i.ZP.createElement(ze.Z,{size:"tiny",ripple:!0,fluid:!0,onClick:O},q(o?"ProfileJoinChannel":"ProfileJoinGroup")),Z&&r&&i.ZP.createElement(ze.Z,{size:"tiny",ripple:!0,fluid:!0,onClick:U},q("BotStart")),Z&&c&&i.ZP.createElement(ze.Z,{size:"tiny",ripple:!0,fluid:!0,onClick:F},q("BotRestart")),d&&i.ZP.createElement(ze.Z,{round:!0,ripple:w,color:"translucent",size:"smaller",onClick:$,ariaLabel:"Search in this chat"},i.ZP.createElement("i",{className:"icon-search"})),u&&i.ZP.createElement(ze.Z,{round:!0,color:"translucent",size:"smaller",onClick:E,ariaLabel:"Call"},i.ZP.createElement("i",{className:"icon-phone"}))),Boolean(y)&&i.ZP.createElement(ze.Z,{round:!0,className:"badge-button",ripple:w,color:"translucent",size:"smaller",onClick:D,ariaLabel:q(o?"SubscribeRequests":"MemberRequests")},i.ZP.createElement("i",{className:"icon-user"}),i.ZP.createElement("div",{className:"badge"},y)),i.ZP.createElement(ze.Z,{ref:k,className:R?"active":"",round:!0,ripple:!h.wB,size:"smaller",color:"translucent",disabled:s,ariaLabel:"More actions",onClick:A},i.ZP.createElement("i",{className:"icon-more"})),T&&i.ZP.createElement(xt,{chatId:t,threadId:n,isOpen:R,anchor:T,withExtraActions:h.wB||!Z,isChannel:o,canStartBot:r,canRestartBot:c,canSubscribe:l,canSearch:d,canCall:u,canMute:g,canViewStatistics:f,canLeave:p,canEnterVoiceChat:v,canCreateVoiceChat:I,onSubscribeChannel:O,onSearchClick:$,onClose:x,onCloseAnimationEnd:L}))})));var Ot=n(4399),Ut=n(6202),Ft=n(862);function Dt(e){var t;const n=e&&(0,d.DH)(e),a=null==e||null===(t=e.content)||void 0===t?void 0:t.sticker,o=n&&a&&!(0,h.on)()&&n.includes("image/webp"),[r,c]=(0,i.eJ)(Ft.Hu),l=null==e?void 0:e.id;return(0,i.bt)((()=>{o&&(0,Ft.p6)(`b64-${l}`,n).then(c).catch((e=>{s.eM&&console.error(e)}))}),[l,o,n]),o?r:n}var $t=n(7551),qt=n(8512),jt=n(996);function Gt(e,t,n,a,s){return`M${e},${t+s}a${s},${s},0,0,1,\n ${n},0v${a-2*s}a${s},${s},0,0,1,${-n},0Z`}const Ht=(0,i.X$)((e=>{let{count:t,index:n}=e;const a=(0,i.sO)(null),s=(0,i.Ye)((()=>function(e,t){const n=e-t-1,a=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),s=function(e,t){let n=36;return 1===e?n=36:2===e?n=17:3===e?n=1===t?12:11:(4===e||e>3)&&(n=7.5),n}(e,n),i=function(e,t){return e<=3?36:t*e+2*(e-1)}(e,a),o=`clipPath${e}`,r=function(e,t,n){let a="";if(3===n)a=Gt(0,0,2,t,1)+Gt(0,12,2,t+1,1)+Gt(0,25,2,t,1);else for(let e=0;e\n \n `}(o,a,e),c=function(e,t,n){return 1===n?0:2===n?0===e?0:t+2:3===n?0===e?0:1===e?12:25:(t+2)*e}(n,a,e),l=function(e,t,n,a){return t<=4||e<=1?0:e>=t-2?a-36:(n+4)/2+(e-2)*(n+2)}(n,e,a,i);return{markHeight:s,clipPath:r,markTranslateY:c,trackTranslateY:l,trackHeight:i,clipPathId:o}}(t,n)),[t,n]);if((0,i.d4)((()=>{if(!a.current)return;const{trackHeight:e,trackTranslateY:t,markHeight:n,markTranslateY:i,clipPathId:o,clipPath:r}=s,c=a.current.firstElementChild;if(null!=a&&a.current){const s=a.current,{style:l}=s;l.height=`${e}px`,l.transform=`translateY(-${t}px)`,l.clipPath=`url("#${o}")`;const d=s.querySelector("svg"),u=s.querySelector("div"),m=s.querySelector("defs");d||c&&(c.innerHTML=` ${r} `),m&&(m.innerHTML=r),u&&(u.style.height=`${n}px`,u.style.transform=`translateY(${i}px)`)}}),[s]),1===t)return i.ZP.createElement("div",{className:"pinned-message-border"},i.ZP.createElement("div",{className:"pinned-message-border-wrapper-1",ref:a}));const{trackHeight:o,trackTranslateY:r,markHeight:c,markTranslateY:l,clipPathId:d}=s;return i.ZP.createElement("div",{className:(0,fe.Z)("pinned-message-border",t>4&&"pinned-message-border-mask")},i.ZP.createElement("div",{className:"pinned-message-border-wrapper",ref:a,style:`clip-path: url("#${d}"); width: 2px;\n height: ${o}px; transform: translateY(-${r}px);`},i.ZP.createElement("span",null),i.ZP.createElement("div",{className:"pinned-message-border-mark",style:`height: ${c}px; transform: translateY(${l}px);`})))})),_t=(0,i.X$)((e=>{let{message:t,count:n,index:a,customTitle:s,className:o,onUnpinMessage:r,onClick:c,onAllPinnedClick:l}=e;const u=(0,Fe.Z)(),m=Dt(t),h=(0,Ut.Z)((0,d.Ti)(t,"pictogram")),g=(0,jt.e)(u,t,Boolean(m)),[f,p,v]=(0,Oe.Z)(),I=(0,i.I4)((()=>{v(),r&&r(t.id)}),[v,r,t.id]);return i.ZP.createElement("div",{className:(0,fe.Z)("HeaderPinnedMessage-wrapper",o)},n>1&&i.ZP.createElement(ze.Z,{round:!0,size:"smaller",color:"translucent",className:"pin-list-button",ariaLabel:u("EventLogFilterPinnedMessages"),onClick:l},i.ZP.createElement("i",{className:"icon-pin-list"})),r&&i.ZP.createElement(ze.Z,{round:!0,size:"smaller",color:"translucent",ariaLabel:u("UnpinMessageAlertTitle"),className:"unpin-button",onClick:p},i.ZP.createElement("i",{className:"icon-close"})),i.ZP.createElement($t.Z,{isOpen:f,onClose:v,text:"Would you like to unpin this message?",confirmLabel:"Unpin",confirmHandler:I}),i.ZP.createElement("div",{className:"HeaderPinnedMessage",onClick:c,dir:u.isRtl?"rtl":void 0},i.ZP.createElement(Ht,{count:n,index:a}),m&&function(e,t){const{width:n,height:a}=(0,Ot.W7)();return i.ZP.createElement("img",{src:t||e,width:n,height:a,alt:""})}(m,h),i.ZP.createElement("div",{className:"message-text"},i.ZP.createElement("div",{className:"title",dir:"auto"},s||`${u("PinnedMessage")} ${a>0?"#"+(n-a):""}`),i.ZP.createElement("p",{dir:"auto"},g)),i.ZP.createElement(qt.Z,null)))}));var zt=n(396),Vt=n(4532),Xt=n(3186);function Kt(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"image/png";const a=e instanceof Blob?URL.createObjectURL(e):e,s=new Image;return new Promise((i=>{s.onload=()=>{Wt(s,s.width*t,s.height*t,n).then((e=>{if(!e)throw new Error("Image resize failed!");return URL.createObjectURL(e)})).then(i).finally((()=>{e instanceof Blob&&URL.revokeObjectURL(a)}))},s.src=a}))}async function Wt(e,t,n){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"image/png";if(!("createImageBitmap"in window))return Yt(e,t,n,void 0,a);try{const s=await window.createImageBitmap(e,{resizeWidth:t,resizeHeight:n,resizeQuality:"high"});if(s.height!==n||s.width!==t)throw new Error("Image bitmap resize not supported!");return await new Promise((e=>{const t=document.createElement("canvas");t.width=s.width,t.height=s.height;const n=t.getContext("bitmaprenderer");n?n.transferFromImageBitmap(s):t.getContext("2d").drawImage(s,0,0),t.toBlob(e,a)}))}catch(s){return Yt(e,t,n,void 0,a)}}function Yt(e,t,n){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:.5,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"image/png";const i=document.createElement("canvas"),o=i.getContext("2d"),r=document.createElement("canvas"),c=r.getContext("2d");if(i.width=t,i.height=n,e.width*a>t){const n=1/a;let s={width:Math.floor(e.width*a),height:Math.floor(e.height*a)};for(r.width=s.width,r.height=s.height,c.drawImage(e,0,0,s.width,s.height);s.width*a>t;)s={width:Math.floor(s.width*a),height:Math.floor(s.height*a)},c.drawImage(r,0,0,s.width*n,s.height*n,0,0,s.width,s.height);o.drawImage(r,0,0,s.width,s.height,0,0,i.width,i.height)}else o.drawImage(e,0,0,i.width,i.height);return new Promise((e=>{i.toBlob(e,s)}))}var Jt=n(4524);const Qt={width:200,height:200},en=115,tn=(e,t,n)=>{const{audio:a,voice:s}=(0,d.qp)(e),o=a?a.title||a.fileName:s?"Voice message":"",r=a&&a.performer||t&&(0,d.OU)(I.i0,t),c=n&&(0,d.U)(I.i0,n)||"Telegram",l=a&&(0,d.MR)(a)&&(0,d.Ti)(e,"pictogram"),u=t&&(0,d.RT)(t,"big"),m=a&&l||s&&u,h=(0,Ut.Z)(m),g=(0,i.Ye)((()=>function(e,t,n){if(!n)return Qt;if(e){if(!e.thumbnailSizes||0===e.thumbnailSizes.length)return;const t=e.thumbnailSizes.find((e=>"m"===e.type));return t||e.thumbnailSizes[0]}return t?Ot.vY:void 0}(a,s,h)),[a,h,s]),{result:f}=((e,t,n)=>{const[a,s]=(0,i.eJ)(!1),[o,r]=(0,i.eJ)(),[c,l]=(0,i.eJ)(n);return(0,i.d4)((()=>{s(!0);let e=!1;return function(e,t){if(!e)return Promise.resolve(Jt);if(!t)return function(e,t,n){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"image/png";const s=e instanceof Blob?URL.createObjectURL(e):e,i=new Image;return new Promise((o=>{i.onload=()=>{Wt(i,t,n,a).then((e=>{if(!e)throw new Error("Image resize failed!");return URL.createObjectURL(e)})).then(o).finally((()=>{e instanceof Blob&&URL.revokeObjectURL(s)}))},i.src=s}))}(e,en,en);const n=Math.min(t.width,t.height);return n{e||(s(!1),l(t))}),(t=>{e||(s(!1),r(t))})),()=>{e=!0}}),t),{isLoading:a,error:o,result:c}})(0,[h,g],Jt);return(0,i.Ye)((()=>(0,Vt.Of)({title:o,artist:r,album:c,artwork:[{src:f}]})),[c,r,o,f])};var nn=n(2340),an=n(8051);const sn=(0,a.c$)(((e,t)=>{let{message:n}=t;const a=(0,c.Ur)(e,n),s=(0,c.Z1)(e,n.chatId),{volume:i,playbackRate:o,isMuted:r}=e.audioPlayer;return{sender:a,chat:s,volume:i,playbackRate:o,isMuted:r}}))((e=>{let{message:t,className:n,noUi:s,sender:o,chat:r,volume:c,playbackRate:l,isMuted:u}=e;const{setAudioPlayerVolume:m,setAudioPlayerPlaybackRate:g,setAudioPlayerMuted:f,focusMessage:p,closeAudioPlayer:v}=(0,a.Sv)(),I=(0,Fe.Z)(),{audio:y,voice:w,video:Z}=(0,d.qp)(t),P=Boolean(w||Z),C=o?(0,d.OU)(I,o):void 0,b=X.UV((0,d.Ti)(t,"inline")),S=tn(t,o,r),{playPause:E,stop:M,isPlaying:k,requestNextTrack:R,requestPreviousTrack:N,isFirst:T,isLast:B,setVolume:A,toggleMuted:x,setPlaybackRate:L}=(0,Xt.Z)((0,zt.An)(t),(0,d.XV)(t),P?"voice":"audio",b,void 0,S,void 0,!0,void 0,void 0,(0,d.CI)(t),!0),O=P&&k;(0,i.d4)((()=>{if(O)return Q.Z.disableRefresh(),()=>{Q.Z.enableRefresh()}}),[O]);const U=(0,i.I4)((()=>{p({chatId:t.chatId,messageId:t.id})}),[p,t.chatId,t.id]),F=(0,i.I4)((()=>{k&&E(),v(),(0,Vt.Ay)(),M()}),[v,k,E,M]),D=(0,i.I4)((e=>{m({volume:e/100}),f({isMuted:!1}),A(e/100)}),[f,m,A]),$=(0,i.I4)((()=>{h.$b&&!h.cj||(x(),f({isMuted:!u}))}),[u,f,x]),q=(0,i.I4)((()=>{1===l?(L(1.8),g({playbackRate:1.8})):(L(1),g({playbackRate:1}))}),[l,g,L]),j=(0,i.Ye)((()=>0===c||u?"icon-muted":c<.3?"icon-volume-1":c<.6?"icon-volume-2":"icon-volume-3"),[c,u]);if(!s)return i.ZP.createElement("div",{className:(0,fe.Z)("AudioPlayer",n),dir:I.isRtl?"rtl":void 0},i.ZP.createElement(ze.Z,{round:!0,ripple:!h.wB,color:"translucent",size:"smaller",className:"player-button",disabled:T(),onClick:N,ariaLabel:"Previous track"},i.ZP.createElement("i",{className:"icon-skip-previous"})),i.ZP.createElement(ze.Z,{round:!0,ripple:!h.wB,color:"translucent",size:"smaller",className:(0,fe.Z)("toggle-play","player-button",k?"pause":"play"),onClick:E,ariaLabel:k?"Pause audio":"Play audio"},i.ZP.createElement("i",{className:"icon-play"}),i.ZP.createElement("i",{className:"icon-pause"})),i.ZP.createElement(ze.Z,{round:!0,ripple:!h.wB,color:"translucent",size:"smaller",className:"player-button",disabled:B(),onClick:R,ariaLabel:"Next track"},i.ZP.createElement("i",{className:"icon-skip-next"})),i.ZP.createElement("div",{className:"AudioPlayer-content",onClick:U},y?function(e){const{title:t,performer:n,fileName:a}=e;return i.ZP.createElement(i.ZP.Fragment,null,i.ZP.createElement("div",{className:"title",dir:"auto"},(0,nn.Z)(t||a)),n&&i.ZP.createElement("div",{className:"subtitle",dir:"auto"},(0,nn.Z)(n)))}(y):function(e,t){return i.ZP.createElement(i.ZP.Fragment,null,i.ZP.createElement("div",{className:"title",dir:"auto"},t&&(0,nn.Z)(t)),i.ZP.createElement("div",{className:"subtitle",dir:"auto"},e))}(I("AttachAudio"),C),i.ZP.createElement(qt.Z,null)),i.ZP.createElement(ze.Z,{round:!0,className:"player-button volume-button",color:"translucent",size:"smaller",ariaLabel:"Volume",withClickPropagation:!0},i.ZP.createElement("i",{className:j,onClick:$}),!h.cj&&i.ZP.createElement(i.ZP.Fragment,null,i.ZP.createElement("div",{className:"volume-slider-spacer"}),i.ZP.createElement("div",{className:"volume-slider"},i.ZP.createElement(an.Z,{bold:!0,value:u?0:100*c,onChange:D})))),P&&i.ZP.createElement(ze.Z,{round:!0,className:(0,fe.Z)("playback-button",1!==l&&"applied"),color:"translucent",size:"smaller",ariaLabel:"Playback Rate",ripple:!h.wB,onClick:q},i.ZP.createElement("span",{className:"playback-button-inner"},"2Х")),i.ZP.createElement(ze.Z,{round:!0,className:"player-close",color:"translucent",size:"smaller",onClick:F,ariaLabel:"Close player"},i.ZP.createElement("i",{className:"icon-close"})))}));var on=n(2431),rn=n(172);const cn=(0,i.X$)((0,a.c$)(((e,t)=>{let{chatId:n}=t;const a=(0,c.Z1)(e,n),s=(0,on.Bj)(e,n);return{groupCall:s,usersById:e.users.byId,chatsById:e.chats.byId,activeGroupCallId:e.groupCalls.activeGroupCallId,isActive:(s?s.participantsCount>0&&s.isLoaded:a&&a.isCallNotEmpty&&a.isCallActive)&&e.groupCalls.activeGroupCallId!==(null==s?void 0:s.id)}}))((e=>{let{chatId:t,isActive:n,groupCall:s,hasPinnedOffset:o,usersById:r,chatsById:c}=e;const{joinGroupCall:l,subscribeToGroupCallUpdates:d}=(0,a.Sv)(),u=(0,Fe.Z)(),m=(0,i.I4)((()=>{l({chatId:t})}),[l,t]),h=null==s?void 0:s.participants,g=(0,i.Ye)((()=>h?Object.values(h).filter(((e,t)=>t<3)).map((e=>{let{id:t,isUser:n}=e;if(n){if(!r[t])return;return{user:r[t]}}if(c[t])return{chat:c[t]}})).filter(Boolean):[]),[c,h,r]);if((0,i.d4)((()=>{if(null!=s&&s.id&&(n||!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,n,d]),s)return i.ZP.createElement("div",{className:(0,fe.Z)("GroupCallTopPane",o&&"has-pinned-offset",!n&&"is-hidden"),onClick:m},i.ZP.createElement("div",{className:"info"},i.ZP.createElement("span",{className:"title"},u("VoipGroupVoiceChat")),i.ZP.createElement("span",{className:"participants"},u("Participants",s.participantsCount||0,"i"))),i.ZP.createElement("div",{className:"avatars"},g.map((e=>{if(e)return e.user?i.ZP.createElement(rn.Z,{key:e.user.id,user:e.user}):i.ZP.createElement(rn.Z,{key:e.chat.id,chat:e.chat})}))),i.ZP.createElement(ze.Z,{round:!0,className:"join"},u("VoipChatJoin")))})));var ln=n(4605);const dn=(0,i.X$)((0,a.c$)(((e,t)=>{let{chatId:n}=t;return{currentUserId:e.currentUserId,chat:(0,c.Z1)(e,n),user:(0,d.YC)(n)?(0,c.dy)(e,n):void 0}}))((e=>{let{chatId:t,className:n,chat:s,user:o,settings:r,currentUserId:c}=e;const{openAddContactDialog:l,blockContact:u,reportSpam:m,deleteChat:h,leaveChannel:g,deleteChatUser:f,deleteHistory:p,toggleChatArchived:v,hideChatReportPanel:I}=(0,a.Sv)(),y=(0,Fe.Z)(),[w,Z,P]=(0,Oe.Z)(),[C,b]=(0,i.eJ)(!0),[S,E]=(0,i.eJ)(!0),{accessHash:M}=s||{},{isAutoArchived:k,canReportSpam:R,canAddContact:N,canBlockContact:T}=r||{},B=s&&(0,d.G9)(s),A=(0,i.I4)((()=>{l({userId:t}),k&&v({chatId:t})}),[l,k,v,t]),x=(0,i.I4)((()=>{P(),u({contactId:t,accessHash:M}),R&&C&&m({chatId:t}),S&&h({chatId:t})}),[M,u,P,h,m,R,S,C,t]),L=(0,i.I4)((()=>{I({chatId:t})}),[t,I]),O=(0,i.I4)((()=>{P(),m({chatId:t}),B?(f({chatId:t,userId:c}),p({chatId:t,shouldDeleteForAll:!1})):g({chatId:t})}),[t,P,c,f,p,B,g,m]);if(r)return i.ZP.createElement("div",{className:(0,fe.Z)("ChatReportPanel",n),dir:y.isRtl?"rtl":void 0},N&&i.ZP.createElement(ze.Z,{isText:!0,fluid:!0,size:"tiny",className:"UserReportPanel--Button",onClick:A},y("lng_new_contact_add")),T&&i.ZP.createElement(ze.Z,{color:"danger",isText:!0,fluid:!0,size:"tiny",className:"UserReportPanel--Button",onClick:Z},y("lng_new_contact_block")),R&&!T&&i.ZP.createElement(ze.Z,{color:"danger",isText:!0,fluid:!0,size:"tiny",className:"UserReportPanel--Button",onClick:Z},y("lng_report_spam_and_leave")),i.ZP.createElement(ze.Z,{round:!0,ripple:!0,size:"tiny",color:"translucent",onClick:L,ariaLabel:y("Close")},i.ZP.createElement("i",{className:"icon-close"})),i.ZP.createElement($t.Z,{isOpen:w,onClose:P,title:y("BlockUserTitle",o?(0,d.Vl)(o):(0,d.U)(y,s)),text:o?y("UserInfo.BlockConfirmationTitle",(0,d.Js)(o)):y("Chat.Confirm.ReportSpam.Group"),isButtonsInOneRow:!0,confirmIsDestructive:!0,confirmLabel:y("Block"),confirmHandler:o?x:O},o&&R&&i.ZP.createElement(ln.Z,{label:y("DeleteReportSpam"),checked:C,onCheck:b}),o&&i.ZP.createElement(ln.Z,{label:y("DeleteThisChat"),checked:S,onCheck:E})))}))),un=(0,i.X$)((0,a.c$)(((e,t)=>{let{chatId:n,threadId:a,messageListType:s}=t;const{isLeftColumnShown:i,lastSyncTime:r,shouldSkipHistoryAnimations:l}=e,d=(0,c.Z1)(e,n),{typingStatus:u}=d||{},{chatId:m,messageId:h}=e.audioPlayer,g=m&&h?(0,c.hj)(e,m,h):void 0;let f;if("pinned"===s){const t=(0,c.KB)(e,n);f=null==t?void 0:t.length}else if("scheduled"===s){const t=(0,c.qy)(e,n);f=null==t?void 0:t.length}else if("thread"===s&&a!==o._f){const t=(0,c.tZ)(e,n,a);f=(null==t?void 0:t.messagesCount)||0}const p={typingStatus:u,isLeftColumnShown:i,isRightColumnShown:(0,c.Jf)(e),isSelectModeActive:(0,c.CA)(e),audioMessage:g,chat:d,messagesCount:f,isChatWithSelf:(0,c.FM)(e,n),isChatWithBot:d&&(0,c.xo)(e,d),lastSyncTime:r,shouldSkipHistoryAnimations:l,currentTransitionKey:Math.max(0,e.messages.messageLists.length-1),connectionState:e.connectionState,isSyncing:e.isSyncing},v=(0,c.Zw)(e,n);if("thread"!==s||!v)return p;if(Object.assign(p,{messagesById:v}),a!==o._f){const t=(0,c.qS)(e,n,a),s=t?(0,c.hj)(e,n,t):void 0,i=s?(0,c.cv)(e,s):void 0;return{...p,pinnedMessageIds:t,canUnpin:!1,topMessageSender:i}}const I=(0,c.KB)(e,n);if(null!=I&&I.length){const t=v[I[0]],{canUnpin:n}=t&&(0,c._k)(e,t,a)||{};return{...p,pinnedMessageIds:I,canUnpin:n}}return p}))((e=>{let{chatId:t,threadId:n,messageListType:r,isReady:c,pinnedMessageIds:l,messagesById:u,canUnpin:m,topMessageSender:g,typingStatus:f,isSelectModeActive:p,isLeftColumnShown:v,isRightColumnShown:I,audioMessage:y,chat:w,messagesCount:Z,isChatWithSelf:P,isChatWithBot:C,lastSyncTime:b,shouldSkipHistoryAnimations:S,currentTransitionKey:E,connectionState:M,isSyncing:k}=e;const{openChatWithInfo:R,pinMessage:N,focusMessage:T,openChat:B,openPreviousChat:A,loadPinnedMessages:x,toggleLeftColumn:L,exitMessageSelectMode:O}=(0,a.Sv)(),U=(0,Fe.Z)(),F=(0,i.sO)(!0),[D,$]=(0,i.eJ)(0),q=Array.isArray(l)?l[D]:l,j=u&&q?u[q]:void 0,G=Array.isArray(l)?l.length:l?1:void 0,H=w&&(0,d.U)(U,w).length,_=g?(0,d.OU)(U,g):void 0,{settings:z}=w||{};(0,i.d4)((()=>{n===o._f&&b&&c&&x({chatId:t})}),[t,x,b,n,c]),(0,i.d4)((()=>{$(0)}),[l]),(0,Nt.Z)(t,q,j);const{width:V}=St(),X=V<=s.ks,K=h.p7&&v,W=(0,i.sO)(null),Y=(0,i.sO)(!0),J=(0,i.I4)((()=>{R({id:t})}),[R,t]),Q=(0,i.I4)((e=>{N({chatId:t,messageId:e,isUnpin:!0})}),[N,t]),ee=(0,i.I4)((()=>{if(j){T({chatId:j.chatId,threadId:n,messageId:j.id});const e=(0,Rt.Z)(G||1,D+1);$(e)}}),[j,T,n,G,D]),te=(0,i.I4)((()=>{B({id:t,threadId:o._f,type:"pinned"})}),[B,t]),ne=(0,i.I4)((()=>{setTimeout((()=>{F.current=!0}),450)}),[]),ae=(0,i.I4)((e=>{if(F.current){if(F.current=!1,h.wB){const e=document.getElementById(s.R2);e&&e.blur()}if(p)return O(),void ne();if(n===o._f&&"thread"===r&&0===E)return h.wB||K?(e.stopPropagation(),B({id:void 0})):L(),void ne();A(),ne()}}),[n,r,E,p,A,K,B,L,O,ne]),se=V>=s.ks&&Vs.l3&&V30),ie=se||V>s._m&&V{const e=W.current;if(e)return ie&&Ze?void(I||se?(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))}),[ie,Ze,se,I]);const{connectionStatusText:Pe}=Ge(U,M,k,!0);function Ce(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return i.ZP.createElement("div",{className:"back-button"},i.ZP.createElement(ze.Z,{round:!0,size:"smaller",color:"translucent",onClick:ae,ariaLabel:U(e?"Close":"Back")},i.ZP.createElement("div",{className:(0,fe.Z)("animated-close-icon",!e&&"state-back")})),t&&i.ZP.createElement(Be,null))}const be=Boolean(de&&me);return i.ZP.createElement("div",{className:"MiddleHeader",ref:W},i.ZP.createElement(Ue.Z,{name:S?"none":"slide-fade",activeKey:E},"thread"===r&&n===o._f?i.ZP.createElement(i.ZP.Fragment,null,(X||E>0)&&Ce(K,!0),i.ZP.createElement("div",{className:"chat-info-wrapper",onClick:J},(0,d.YC)(t)?i.ZP.createElement(Bt.Z,{userId:t,typingStatus:f,status:Pe,withDots:Boolean(Pe),withFullInfo:C,withMediaViewer:!0,withUpdatingStatus:!0,noRtl:!0}):i.ZP.createElement(At.Z,{chatId:t,typingStatus:f,status:Pe,withDots:Boolean(Pe),withMediaViewer:!0,withFullInfo:!0,withUpdatingStatus:!0,noRtl:!0}))):"thread"===r?i.ZP.createElement(i.ZP.Fragment,null,Ce(),i.ZP.createElement("h3",null,U("CommentsCount",Z,"i"))):"pinned"===r?i.ZP.createElement(i.ZP.Fragment,null,Ce(),i.ZP.createElement("h3",null,U("PinnedMessagesCount",Z,"i"))):"scheduled"===r?i.ZP.createElement(i.ZP.Fragment,null,Ce(),i.ZP.createElement("h3",null,P?U("Reminders"):U("messages",Z,"i"))):void 0),i.ZP.createElement(cn,{hasPinnedOffset:he&&Boolean(pe)||de&&Boolean(me),chatId:t}),he&&pe&&i.ZP.createElement(_t,{key:t,message:pe,count:ve||0,index:D,customTitle:we,className:(0,fe.Z)(ge,be&&"full-width"),onUnpinMessage:Ie?Q:void 0,onClick:ee,onAllPinnedClick:te}),re&&i.ZP.createElement(dn,{key:t,chatId:t,settings:le,className:ce}),i.ZP.createElement("div",{className:"header-tools"},be&&i.ZP.createElement(sn,{key:(0,d.Tp)(me),message:me,className:ue}),i.ZP.createElement(Lt,{chatId:t,threadId:n,messageListType:r,canExpandActions:!be})))})));var mn=n(2645),hn=n(274);function gn(e){return"albumId"in e}function fn(e,t){let n,a=[],s={originalDate:e[0].date,datetime:(0,L._F)(1e3*e[0].date),senderGroups:[a]};const i=[s];return e.forEach(((o,r)=>{o.isInAlbum?n?(n.messages.push(o),o.content.text&&(n.mainMessage=o)):n={albumId:o.groupedId,messages:[o],mainMessage:o}:a.push(o);const c=e[r+1];if(!n||c&&c.groupedId&&c.groupedId===n.albumId||(a.push(n),n=void 0),c){const e=(0,L._F)(1e3*c.date);s.datetime!==e?(s={originalDate:c.date,datetime:e,senderGroups:[]},i.push(s),a=[],s.senderGroups.push(a)):(c.id===t||o.senderId!==c.senderId||o.isOutgoing!==c.isOutgoing||(0,d.Lo)(o)||(0,d.Lo)(c)||o.forwardInfo&&c.forwardInfo&&(o.forwardInfo.senderUserId!==c.forwardInfo.senderUserId||o.forwardInfo.fromChatId!==c.forwardInfo.fromChatId||o.forwardInfo.hiddenUserName!==c.forwardInfo.hiddenUserName)||o.inlineButtons||c.inlineButtons||c.date-o.date>600)&&(a=[],s.senderGroups.push(a))}})),i}var pn=n(386),vn=n(2202);var In=n(7675),yn=n(539),wn=n(2357),Zn=n(998);var Pn=n(3657);const Cn=h.wZ?1e3:350,bn=h.wB?300:500;var Sn=n(7240);function En(e){return"number"==typeof e}function Mn(e,t){return e?t?238:175:t?238:100}function kn(e,t){const n=(0,d.B4)(e),a=(0,d.MF)(e),s=(0,d.O$)(e)||(0,d.F$)(e),i=(0,d.b7)(e),o=Boolean((0,d.F$)(e)),{width:r,height:c}=s?(0,Ot.Eh)(s,n,a,o,t):(0,Ot.GC)(i,n,a,t),l=Mn(Boolean((0,d.UD)(e)));let u=1;re+t),t)}function Nn(e,t,n){return en?n:e}function Tn(e){const t={width:0,height:0};return e.forEach((e=>{let{dimensions:n,sides:a}=e;2&a&&(t.width=n.width+n.x),4&a&&(t.height=n.height+n.y)})),t}function Bn(e,t,n,a){const s=function(e){return e.map((e=>{const t=kn(e);return t.width/t.height}))}(a.messages),i=function(e){return e.map((e=>e>1.2?"w":e<.8?"n":"q")).join("")}(s),o=function(e){return e.reduce(((e,t)=>t+e),1)/e.length}(s),r=s.length,c=s.some((e=>e>2)),l=(0,Ot.kc)(e,t,!1,n)-(t?2.5:0)*Ot.Gw;let d;const u={ratios:s,proportions:i,averageRatio:o,maxWidth:l,minWidth:100,maxHeight:l,spacing:2};return d=r>=5||c?function(e){let{ratios:t,averageRatio:n,maxWidth:a,minWidth:s,spacing:i,maxHeight:o=4*a/3}=e;const r=function(e,t){return e.map((e=>t>1.1?Nn(e,1,2.75):Nn(e,.6667,1)))}(t,n),c=t.length,l=new Array(c),d=[],u=e=>{const t=[];let n=0;e.forEach((e=>{t.push(((e,t)=>{const n=Rn(r.slice(e,e+t),0);return(a-(t-1)*i)/n})(n,e)),n+=e})),d.push({lineCounts:e,heights:t})};for(let e=1;e!==c;++e){const t=c-e;e<=3&&t<=3&&u([e,t])}for(let e=1;e!==c-1;++e)for(let t=1;t!==c-e;++t){const a=c-e-t;e<=3&&t<=(n<.85?4:3)&&a<=3&&u([e,t,a])}for(let e=1;e!==c-1;++e)for(let t=1;t!==c-e;++t)for(let n=1;n!==c-e-t;++n){const a=c-e-t-n;e<=3&&t<=3&&n<=3&&a<=4&&u([e,t,n,a])}let m,h=0;for(let e=0;e{for(let e=1;e!==a;++e)if(n[e-1]>n[e])return 1.5;return 1})(),u=Math.abs(r-o)*c*l;(!m||u1.4&&t[1]-t[0]<.2?function(e){const{ratios:t,maxWidth:n,spacing:a,maxHeight:s}=e,i=Math.round(Math.min(n/t[0],Math.min(n/t[1],(s-a)/2)));return[{dimensions:{x:0,y:0,width:n,height:i},sides:11},{dimensions:{x:0,y:i+a,width:n,height:i},sides:14}]}(e):"ww"===n||"qq"===n?function(e){const{ratios:t,maxWidth:n,spacing:a,maxHeight:s}=e,i=(n-a)/2,o=Math.round(Math.min(i/t[0],Math.min(i/t[1],s)));return[{dimensions:{x:0,y:0,width:i,height:o},sides:13},{dimensions:{x:i+a,y:0,width:i,height:o},sides:7}]}(e):function(e){const{ratios:t,minWidth:n,maxWidth:a,spacing:s,maxHeight:i}=e,o=Math.round(1.5*n),r=Math.min(Math.round(Math.max(.4*(a-s),(a-s)/t[0]/(1/t[0]+1/t[1]))),a-s-o),c=a-r-s,l=Math.min(i,Math.round(Math.min(c/t[0],r/t[1])));return[{dimensions:{x:0,y:0,width:c,height:l},sides:13},{dimensions:{x:c+s,y:0,width:r,height:l},sides:7}]}(e)}(u):3===r?function(e){const{proportions:t}=e;return"n"===t[0]?function(e){const{maxHeight:t,spacing:n,ratios:a,maxWidth:s,minWidth:i}=e,o=t,r=Math.round(Math.min((t-n)/2,a[1]*(s-n)/(a[2]+a[1]))),c=o-r-n,l=Math.max(i,Math.round(Math.min((s-n)/2,Math.min(r*a[2],c*a[1])))),d=Math.min(Math.round(o*a[0]),s-n-l);return[{dimensions:{x:0,y:0,width:d,height:o},sides:13},{dimensions:{x:d+n,y:0,width:l,height:c},sides:3},{dimensions:{x:d+n,y:c+n,width:l,height:r},sides:6}]}(e):function(e){const{maxWidth:t,ratios:n,maxHeight:a,spacing:s}=e,i=t,o=Math.round(Math.min(i/n[0],.66*(a-s))),r=(t-s)/2,c=Math.min(a-o-s,Math.round(Math.min(r/n[1],r/n[2])));return[{dimensions:{x:0,y:0,width:i,height:o},sides:11},{dimensions:{x:0,y:o+s,width:r,height:c},sides:12},{dimensions:{x:r+s,y:o+s,width:i-r-s,height:c},sides:6}]}(e)}(u):function(e){const{proportions:t}=e;return"w"===t[0]?function(e){let{maxWidth:t,ratios:n,spacing:a,maxHeight:s,minWidth:i}=e;const o=t,r=Math.round(Math.min(o/n[0],.66*(s-a))),c=Math.round((t-2*a)/(n[1]+n[2]+n[3])),l=Math.max(i,Math.round(Math.min(.4*(t-2*a),c*n[1]))),d=Math.round(Math.max(Math.max(i,.33*(t-2*a)),c*n[3])),u=o-l-d-2*a,m=Math.min(s-r-a,c);return[{dimensions:{x:0,y:0,width:o,height:r},sides:11},{dimensions:{x:0,y:r+a,width:l,height:m},sides:12},{dimensions:{x:l+a,y:r+a,width:u,height:m},sides:4},{dimensions:{x:l+a+u+a,y:r+a,width:d,height:m},sides:6}]}(e):function(e){let{maxHeight:t,ratios:n,maxWidth:a,spacing:s,minWidth:i}=e;const o=t,r=Math.round(Math.min(o*n[0],.6*(a-s))),c=Math.round((t-2*s)/(1/n[1]+1/n[2]+1/n[3])),l=Math.round(c/n[1]),d=Math.round(c/n[2]),u=o-l-d-2*s,m=Math.max(i,Math.min(a-r-s,c));return[{dimensions:{x:0,y:0,width:r,height:o},sides:13},{dimensions:{x:r+s,y:0,width:m,height:l},sides:3},{dimensions:{x:r+s,y:l+s,width:m,height:d},sides:2},{dimensions:{x:r+s,y:l+d+2*s,width:m,height:u},sides:6}]}(e)}(u),{layout:d,containerStyle:Tn(d)}}let An;function xn(e){return An||(An=document.createElement("span"),An.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',An.style.whiteSpace="nowrap",An.style.position="absolute",An.style.left="-999px",An.style.opacity=".01",document.body.appendChild(An)),An.innerHTML=e,An.offsetWidth}function Ln(e,t,n,a,s,o){(0,i.bt)((()=>{if(n&&e.current){const t=e.current.closest(".MessageList");(0,yn.Z)(t,e.current,s?"end":"centerOrTop",20,void 0!==a?1e3:void 0,a,void 0,o)}}),[e,t,n,a,s,o])}const On=3*Ot.Gw,Un=Number(Ot.Gw),Fn="data-is-document-group-hover";function Dn(e,t,n,s,o,r,c,l,d,u,m,g,f,p){const{setReplyingToId:v,sendDefaultReaction:I}=(0,a.Sv)(),[y,w,Z]=(0,Oe.Z)(),[P,C,b]=(0,Oe.Z)(),S=(0,i.sO)();return(0,i.d4)((()=>{if(!h.$b||o||!r||m)return;let e;return(0,tt.sf)(t.current,{selectorToPreventScroll:".MessageList",onSwipe:(t,n)=>n===tt.eM.Left&&(e||(e=Date.now()),C(),!0),onRelease:()=>{e&&(v({messageId:n}),setTimeout(b,Math.max(0,150-(Date.now()-e))),e=void 0)}})}),[t,o,n,v,C,b,r,m]),{handleMouseDown:o?void 0:function(e){(0,pn.q)(e),d(e)},handleClick:function(t){if(o)e(t);else if(h.$b)return S.current?(clearInterval(S.current),S.current=void 0,void function(e){const{pageX:t,pageY:a}=e;I({chatId:u,messageId:n,x:t,y:a})}(t)):void(S.current=setTimeout((()=>{S.current=void 0,function(e){if(h.wZ){const t=e.target;if(!t.classList.contains("text-content")&&!t.classList.contains("Message"))return;Q.Z.getIsKeyboardVisible()?setTimeout((()=>{l(e)}),350):l(e)}}(t)}),200))},handleContextMenu:o?c?Ie.Z:void 0:function(t){if(h.wZ){if(t.target.matches("a[href]")||m)return;t.preventDefault(),e()}else l(t)},handleDoubleClick:o?void 0:function(){h.$b||v({messageId:n})},handleContentDoubleClick:h.$b?void 0:function(e){e.stopPropagation()},handleMouseMove:function(e){const t=g.current;if(!t)return;const{clientX:n,clientY:a}=e,{x:s,width:i,y:o,height:r}=t.getBoundingClientRect(),c=Math.abs(f?n-s:s+i-n){const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"ContextMenuContainer",!t);return n?i.ZP.createElement(n,e):void 0})),Hn=(0,i.X$)((0,a.c$)(((e,t)=>{let{message:n}=t;const{byId:a}=e.users,s=n.senderId,{targetUserIds:i,targetChatId:o}=n.content.action||{},r=n.replyToMessageId,l=r?(0,c.hj)(e,n.chatId,r):void 0,u=(0,c._X)(e,n),{direction:m,noHighlight:h}=u&&e.focusedMessage||{},g=(0,c.Z1)(e,n.chatId),f=g&&((0,d.eA)(g)||s===n.chatId);return{usersById:a,senderUser:!f&&s?(0,c.dy)(e,s):void 0,senderChat:f?g:void 0,targetChatId:o,targetUserIds:i,targetMessage:l,isFocused:u,...u&&{focusDirection:m,noFocusHighlight:h}}}))((e=>{let{message:t,observeIntersection:n,isEmbedded:a,appearanceOrder:s=0,isLastInList:o,usersById:r,senderUser:c,senderChat:l,targetUserIds:u,targetMessage:m,targetChatId:h,isFocused:g,focusDirection:f,noFocusHighlight:p}=e;const v=(0,i.sO)(null);(0,Pn._N)(v,n),(0,Nt.Z)(t.chatId,t.replyToMessageId,m),Ln(v,t.chatId,g,f,p);const I=(0,Fe.Z)(),y=s<=0,[w,Z]=(0,Oe.Z)(y);(0,i.d4)((()=>{y||setTimeout(Z,10*s)}),[s,Z,y]);const{transitionClassNames:P}=(0,ye.Z)(w,void 0,y,!1),C=(0,i.Ye)((()=>u?u.map((e=>null==r?void 0:r[e])).filter(Boolean):void 0),[u,r]),b=(0,jn.D)(I,t,c,l,C,m,h,{asTextWithSpoilers:a}),{isContextMenuOpen:S,contextMenuPosition:E,handleBeforeContextMenu:M,handleContextMenu:k,handleContextMenuClose:R,handleContextMenuHide:N}=(0,Sn.Z)(v),T=void 0!==E;if(a)return i.ZP.createElement("span",{className:"embedded-action-message"},b);const B=(0,fe.Z)("ActionMessage message-list-item",g&&!p&&"focused",T&&"has-menu-open",o&&"last-in-list",P);return i.ZP.createElement("div",{ref:v,id:(0,d.d0)(t.id),className:B,"data-message-id":t.id,onMouseDown:e=>{(0,pn.q)(e),M(e)},onContextMenu:k},i.ZP.createElement("span",null,b),E&&i.ZP.createElement(Gn,{isOpen:S,anchor:E,message:t,messageListType:"thread",onClose:R,onCloseAnimationEnd:N}))}))),_n=e=>{let{className:t,message:n,sender:a,title:s,customText:o,isProtected:r,observeIntersection:c,onClick:l}=e;const u=(0,i.sO)(null),m=(0,Pn.Op)(u,c),h=(0,Ut.Z)(n&&(0,d.Ti)(n,"pictogram"),!m),g=Dt(n),f=Boolean(n&&(0,d.Y5)(n)),p=(0,Fe.Z)(),v=a&&(0,d.OU)(p,a);return i.ZP.createElement("div",{ref:u,className:(0,fe.Z)("EmbeddedMessage",t),onClick:n?l:void 0},g&&function(e,t,n,a){const{width:s,height:o}=(0,Ot.W7)();return i.ZP.createElement(i.ZP.Fragment,null,i.ZP.createElement("img",{src:t||e,width:s,height:o,alt:"",className:n?"round":"",draggable:!a}),a&&i.ZP.createElement("span",{className:"protector"}))}(g,h,f,r),i.ZP.createElement("div",{className:"message-text"},i.ZP.createElement("p",{dir:"auto"},n?(0,d.Lo)(n)?i.ZP.createElement(Hn,{message:n,isEmbedded:!0}):(0,jt.e)(p,n,Boolean(g)):o||" "),i.ZP.createElement("div",{className:"message-title",dir:"auto"},(0,nn.Z)(v||s||" "))))};var zn=n(2535),Vn=n(4752),Xn=n(8018),Kn=n(8198),Wn=n(7799);const Yn=(0,i.X$)((e=>{var t,n;let{reaction:s,activeReaction:r,isInMeta:c,availableReactions:l}=e;const{stopActiveReaction:d}=(0,a.Sv)(),u=null==l?void 0:l.find((e=>e.reaction===s)),m=null==u||null===(t=u.centerIcon)||void 0===t?void 0:t.id,h=null==u||null===(n=u.aroundAnimation)||void 0===n?void 0:n.id,g=(0,Ut.Z)(`sticker${m}`,!m,o.IU.Lottie),f=(0,Ut.Z)(`sticker${h}`,!h,o.IU.Lottie),p=Boolean((null==r?void 0:r.reaction)===s&&g&&f),{shouldRender:v,transitionClassNames:I}=(0,ye.Z)(p,void 0,!0,"slow"),y=(0,i.I4)((()=>{d({messageId:null==r?void 0:r.messageId,reaction:s})}),[null==r?void 0:r.messageId,s,d]),[w,Z,P]=(0,Oe.Z)(),C=!p||!w,b=(0,fe.Z)("ReactionAnimatedEmoji",c&&"in-meta",v&&"is-animating");return i.ZP.createElement("div",{className:b},C&&i.ZP.createElement(Kn.Z,{reaction:s}),v&&i.ZP.createElement(i.ZP.Fragment,null,i.ZP.createElement(Wn.Z,{key:m,id:`reaction_emoji_${m}`,className:I,size:30,animationData:g,play:!0,noLoop:!0,forceOnHeavyAnimation:!0,onLoad:Z,onEnded:P}),i.ZP.createElement(Wn.Z,{key:h,id:`reaction_effect_${h}`,className:(0,fe.Z)("effect",I),size:100,animationData:f,play:!0,noLoop:!0,forceOnHeavyAnimation:!0,onEnded:y})))})),Jn=(0,i.X$)((e=>{var t;let{message:n,outgoingStatus:a,signature:s,onClick:o,withReactions:r,activeReaction:c,withReactionOffset:l,availableReactions:d,reactionMessage:u}=e;const m=(0,Fe.Z)(),[h,g]=(0,Oe.Z)(),f=r&&(null==u||null===(t=u.reactions)||void 0===t?void 0:t.results.filter((e=>e.count>0))),p=(0,i.Ye)((()=>{if(!h)return;const e=(0,L.SA)(1e3*n.date,m.code),t=n.isEdited&&(0,L.SA)(1e3*n.editDate,m.code),a=n.forwardInfo&&(0,L.SA)(1e3*n.forwardInfo.date,m.code);let s=e;return t&&(s+="\n",s+=m("lng_edited_date").replace("{date}",t)),a&&(s+="\n",s+=m("lng_forwarded_date").replace("{date}",a)),s}),[h,m,n]);return i.ZP.createElement("span",{className:(0,fe.Z)("MessageMeta",l&&"reactions-offset"),dir:m.isRtl?"rtl":"ltr",onClick:o},f&&f.map((e=>i.ZP.createElement(Yn,{activeReaction:c,reaction:e.reaction,isInMeta:!0,availableReactions:d}))),Boolean(n.views)&&i.ZP.createElement(i.ZP.Fragment,null,i.ZP.createElement("span",{className:"message-views"},(0,Re.bi)(n.views)),i.ZP.createElement("i",{className:"icon-channelviews"})),s&&i.ZP.createElement("span",{className:"message-signature"},(0,nn.Z)(s)),i.ZP.createElement("span",{className:"message-time",title:p,onMouseEnter:g},n.isEdited&&`${m("EditedMessage")} `,(0,L.mr)(m,1e3*n.date)),a&&i.ZP.createElement(Xn.Z,{status:a}))}));var Qn=n(692),ea=n(4753);const ta=e=>{let{message:t,observeIntersection:n,observeIntersectionForPlaying:a,shouldLoop:o,lastSyncTime:r}=e;const c=(0,i.sO)(null),[l,u,m]=(0,Oe.Z)(),g=t.content.sticker,{isLottie:f,stickerSetId:p,isVideo:v}=g,I=h.Hh,y=p===s.$E,w=(0,Pn.Op)(c,n),Z=(0,Pn.Op)(c,a),P=g.isPreloadedGlobally?`sticker${g.id}`:(0,d.Ti)(t,"inline"),C=v&&!I&&(g.isPreloadedGlobally?`sticker${g.id}?size=m`:(0,d.Ti)(t,"pictogram")),b=(0,Ut.Z)(C),S=Dt(t),E=b||S,M=(0,Ut.Z)(P,!w,(0,d.kG)(t,"inline"),r),k=Boolean(M),[R,N]=(0,Oe.Z)(k),T=f?R:k,B=(0,Qn.Z)(T),{width:A,height:x}=(0,Ot.Wr)(g),L=(0,fe.Z)("thumbnail",!S&&"empty"),O=(0,fe.Z)("Sticker media-inner",y&&"inactive");return(0,i.d4)((()=>{if(!v||!c.current)return;const e=c.current.querySelector("video");e&&(Z?(0,ea.Z)(e):e.pause())}),[v,Z]),i.ZP.createElement("div",{ref:c,className:O,onClick:y?void 0:u},(!T||v&&!I)&&i.ZP.createElement("img",{src:E,width:A,height:x,alt:"",className:L}),!f&&!v&&i.ZP.createElement("img",{src:M,width:A,height:x,alt:"",className:(0,fe.Z)("full-media",B)}),v&&I&&T&&i.ZP.createElement("video",{src:M,width:A,height:x,autoPlay:Z,playsInline:!0,loop:o,muted:!0}),f&&k&&i.ZP.createElement(Wn.Z,{key:P,className:(0,fe.Z)("full-media",B),id:P,animationData:M,size:A,play:Z,noLoop:!o,onLoad:N}),i.ZP.createElement(ke.Z,{isOpen:l,fromSticker:g,onClose:m}))};var na=n(7854),aa=n(2566),sa=n(5866);function ia(e,t){return(0,sa.Z)((0,d.DH)(e),Boolean(t),h.wB&&!h.vX)}const oa={dark:{outgoing:"rgb(135,116,225)",incoming:"rgb(33,33,33)"},light:{outgoing:"rgb(238,255,222)",incoming:"rgb(255,255,255)"}};function ra(e,t,n,a,s){return a?Promise.resolve(oa[s||"light"][t?"outgoing":"incoming"]):async function(e,t){const n=new Image;n.src=e,n.width||await new Promise((e=>{n.onload=e}));const a=document.createElement("canvas"),s=a.getContext("2d");a.width=n.width,a.height=n.height,s.drawImage(n,0,0,n.width,n.height);const i=t?n.width-1:0,o=n.height-1;return`rgba(${Array.from(s.getImageData(i,o,1,1).data).join(",")})`}(e,t)}var ca=n(9196);const la=e=>{let{id:t,message:n,observeIntersection:a,noAvatars:o,canAutoLoad:r,isInSelectMode:c,isSelected:l,uploadProgress:u,size:m="inline",dimensions:h,nonInteractive:g,shouldAffectAppendix:f,isDownloading:p,isProtected:v,theme:I,onClick:y,onCancelUpload:w}=e;const Z=(0,i.sO)(null),P=((0,d.O$)(n)||(0,d.F$)(n)).blobUrl,C=(0,Pn.Op)(Z,a),[b,S]=(0,i.eJ)(r),E=b&&C,{mediaData:M,loadProgress:k}=(0,aa.Z)((0,d.Ti)(n,m),!E),R=P||M,N=ia(n,R),{loadProgress:T}=(0,aa.Z)((0,d.Ti)(n,"download"),!p),{isUploading:B,isTransferring:A,transferProgress:x}=(0,d.Sc)(n,u||(p?T:k),E&&!R),L=!1===(0,Mt.Z)(b),O=(0,Qn.Z)(R),{shouldRender:U,transitionClassNames:F}=(0,ye.Z)(A,void 0,L,"slow"),{shouldRender:D,transitionClassNames:$}=(0,ye.Z)(!R&&!b),q=(0,i.I4)((()=>{B?w&&w(n):R?y&&y(n.id):S((e=>!e))}),[R,B,n,w,y]),j=(0,d.B4)(n);(0,i.bt)((()=>{if(!f)return;const e=Z.current.closest(".message-content");R?ra(R,j,0,l,I).then((t=>{e.style.setProperty("--appendix-bg",t),e.setAttribute(s.s2,"")})):e.classList.add("has-appendix-thumb")}),[R,j,f,c,l,I]);const{width:G,height:H,isSmall:_}=h||kn(n,o),z=(0,fe.Z)("media-inner",!B&&!g&&"interactive",_&&"small-image",G===H&&"square-image"),V=h?`width: ${G}px; height: ${H}px; left: ${h.x}px; top: ${h.y}px;`:"";return i.ZP.createElement("div",{id:t,ref:Z,className:z,style:V,onClick:B?void 0:q},i.ZP.createElement("canvas",{ref:N,className:"thumbnail",style:`width: ${G}px; height: ${H}px`}),i.ZP.createElement("img",{src:R,className:`full-media ${O}`,width:G,height:H,alt:"",draggable:!v}),v&&i.ZP.createElement("span",{className:"protector"}),U&&!D&&i.ZP.createElement("div",{className:`media-loading ${F}`},i.ZP.createElement(ca.Z,{progress:x,onClick:B?q:void 0})),D&&i.ZP.createElement("i",{className:(0,fe.Z)("icon-download",$)}),A&&i.ZP.createElement("span",{className:"message-transfer-progress"},Math.round(100*x),"%"))};var da=n(2019),ua=n(6898);function ma(e,t){var n;const a=(0,i.sO)(null===(n=e.current)||void 0===n?void 0:n.paused),s=(0,i.sO)();s.current=t;const o=(0,i.I4)((()=>{e.current&&(a.current=!e.current.paused,a.current&&e.current.pause())}),[e]),r=(0,i.I4)((()=>{e.current&&a.current&&s.current&&document.body.contains(e.current)&&(0,ea.Z)(e.current)}),[e]),c=(0,i.I4)((()=>{(0,E.T2)(r)}),[r]);(0,we.Z)(o,c),(0,ge.ZP)(o,r)}function ha(){return ha=Object.assign||function(e){for(var t=1;t{var t;let{id:n,message:s,observeIntersection:r,noAvatars:c,canAutoLoad:l,canAutoPlay:u,uploadProgress:m,lastSyncTime:h,dimensions:g,onClick:f,onCancelUpload:p,isDownloading:v,isProtected:I}=e;const y=(0,i.sO)(null),w=(0,i.sO)(null),Z=(0,d.b7)(s)||(0,d.Cg)(s),P=Z.blobUrl,C=(0,Pn.Op)(y,r),[b,S]=(0,i.eJ)(l),E=Boolean(b&&C&&h),[M,k]=(0,i.eJ)(u),R=(0,Ut.Z)((0,d.Ti)(s,"pictogram"),!(C&&h),(0,d.kG)(s,"pictogram"),h),N=(0,Qn.Z)(R),{mediaData:T,loadProgress:B}=(0,aa.Z)((0,d.Ti)(s,"inline"),!E,(0,d.kG)(s,"inline"),h),A=P||T,x=Boolean(C&&A),O=ia(s,R),{loadProgress:U}=(0,aa.Z)((0,d.Ti)(s,"download"),!v,o.IU.BlobUrl,h),{isBuffered:F,bufferingHandlers:D}=(0,da.Z)(!l),{isUploading:$,isTransferring:q,transferProgress:j}=(0,d.Sc)(s,m||(v?U:B),E&&!F||v),G=!1===(0,Mt.Z)(b),{shouldRender:H,transitionClassNames:_}=(0,ye.Z)(q,void 0,G),{shouldRender:z,transitionClassNames:V}=(0,ye.Z)(b&&!M&&!H),[X,K]=(0,i.eJ)(0),W=(0,i.I4)((e=>{K(Math.max(0,e.currentTarget.currentTime-1))}),[]),Y=(null===(t=w.current)||void 0===t?void 0:t.duration)||Z.duration||0,J=(0,d.B4)(s),Q=(0,d.MF)(s),{width:ee,height:te}=g||(0,Ot.GC)(Z,J,Q,c);ma(w,x),(0,ua.Z)(w,[x]);const ne=(0,i.I4)((()=>{$?p&&p(s):v?(0,a.Sv)().cancelMessageMediaDownload({message:s}):A?A&&!M?(k(!0),w.current.play()):f&&f(s.id):S((e=>!e))}),[$,v,A,M,f,p,s]),ae=(0,fe.Z)("media-inner dark",!$&&"interactive"),se=g?`width: ${ee}px; height: ${te}px; left: ${g.x}px; top: ${g.y}px;`:"";return i.ZP.createElement("div",{ref:y,id:n,className:ae,style:se,onClick:$?void 0:ne},i.ZP.createElement("canvas",{ref:O,className:"thumbnail",style:`width: ${ee}px; height: ${te}px;`}),i.ZP.createElement("img",{src:R,className:(0,fe.Z)("thumbnail",N),style:`width: ${ee}px; height: ${te}px;`,alt:"",draggable:!I}),x&&i.ZP.createElement("video",ha({ref:w,className:"full-media",width:ee,height:te,autoPlay:M,muted:!0,loop:!0,playsInline:!0},D,{draggable:!I,onTimeUpdate:W}),i.ZP.createElement("source",{src:A})),I&&i.ZP.createElement("span",{className:"protector"}),z&&i.ZP.createElement("i",{className:(0,fe.Z)("icon-large-play",V)}),H&&i.ZP.createElement("div",{className:(0,fe.Z)("media-loading",_)},i.ZP.createElement(ca.Z,{progress:j,onClick:ne})),!b&&i.ZP.createElement("i",{className:"icon-download"}),q?i.ZP.createElement("span",{className:"message-transfer-progress"},$||v?`${Math.round(100*j)}%`:"..."):i.ZP.createElement("div",{className:"message-media-duration"},Z.isGif?"GIF":(0,L.k9)(Math.max(Y-X,0))))};var fa=n(6272);const pa=(0,a.c$)(((e,t)=>{let{contact:n}=t;const{countryList:{phoneCodes:a}}=e;return{user:(0,c.dy)(e,n.userId),phoneCodeList:a}}))((e=>{let{contact:t,user:n,phoneCodeList:s}=e;const{openChat:o}=(0,a.Sv)(),{firstName:r,lastName:c,phoneNumber:l,userId:d}=t,u=(0,i.I4)((()=>{o({id:d})}),[o,d]);return i.ZP.createElement("div",{className:(0,fe.Z)("Contact",Boolean(d)&&"interactive"),onClick:d?u:void 0},i.ZP.createElement(rn.Z,{size:"large",user:n,text:r||c}),i.ZP.createElement("div",{className:"contact-info"},i.ZP.createElement("div",{className:"contact-name"},r," ",c),i.ZP.createElement("div",{className:"contact-phone"},(0,fa.WZ)(s,l))))}));var va=n(8974),Ia=n(1218),ya=n(4434),wa=n(6937);function Za(e,t){return t>0?(e/t*100).toFixed():0}const Pa=e=>{let{answer:t,voteResults:n,totalVoters:a,maxVotersCount:s,correctResults:o,shouldAnimate:r}=e;const c=n&&n.find((e=>e.option===t.option)),l=0===o.length||-1!==o.indexOf(t.option),d=o.length>0&&l||(null==c?void 0:c.isChosen),u=c?Za(c.votersCount,a||0):0,[m,h]=(0,i.eJ)(r?0:u),g=(0,i.sO)(null),f=c?Za(c.votersCount,s||0):0,p=m{r&&h(u)}),[r,u]),(0,i.d4)((()=>{const e=g.current;if(e&&r){const t=e.firstElementChild,n=p?"":"stroke-dasharray: 100% 200%; stroke-dashoffset: -44";t?t.setAttribute("style",n):e.innerHTML=`\n \n \n `}}),[p,r]),!n||!c)return;const v=`width: ${f}%; transform:scaleX(${p?0:1})`;return i.ZP.createElement("div",{className:"PollOption",dir:"ltr"},i.ZP.createElement("div",{className:"poll-option-share "+("100"===u?"limit-width":"")},u,"%",d&&i.ZP.createElement("span",{className:(0,fe.Z)("poll-option-chosen",!l&&"wrong",r&&"animate")},i.ZP.createElement("i",{className:l?"icon-check":"icon-close"}))),i.ZP.createElement("div",{className:"poll-option-right"},i.ZP.createElement("div",{className:"poll-option-text",dir:"auto"},(0,nn.Z)(t.text)),i.ZP.createElement("div",{className:(0,fe.Z)("poll-option-answer",d&&!l&&"wrong")},i.ZP.createElement("div",{className:"poll-option-corner",ref:g}),i.ZP.createElement("div",{className:"poll-option-line",style:v}))))},Ca=(0,i.X$)((0,a.c$)(((e,t)=>{let{poll:n}=t;const{recentVoterIds:a}=n.results,{serverTimeOffset:s,users:{byId:i}}=e;return a&&0!==a.length?{recentVoterIds:a,usersById:i,serverTimeOffset:s}:{}}))((e=>{let{message:t,poll:n,recentVoterIds:s,usersById:o,onSendVote:r,serverTimeOffset:c}=e;const{loadMessage:l,openPollResults:d}=(0,a.Sv)(),{id:u,chatId:m}=t,{summary:h,results:g}=n,[f,p]=(0,i.eJ)(!1),[v,I]=(0,i.eJ)([]),[y,w]=(0,i.eJ)(!1),[Z,P]=(0,i.eJ)(!1),[C,b]=(0,i.eJ)(!h.closed&&h.closeDate&&h.closeDate>0?Math.min(h.closeDate-Math.floor(Date.now()/1e3)+c,h.closePeriod):0),S=(0,i.sO)(null),{results:E,totalVoters:M}=g,k=E&&E.some((e=>e.isChosen)),R=!h.closed&&!k,N=!R&&h.isPublic&&Number(g.totalVoters)>0,T=R&&h.multipleChoice,B=E?Math.max(...E.map((e=>e.votersCount))):M,A=E?E.reduce(((e,t)=>(t.isCorrect&&e.push(t.option),e)),[]):[],x=h.answers.map((e=>({label:e.text,value:e.option,hidden:Boolean(h.quiz&&h.closePeriod&&C<=0)})));(0,i.d4)((()=>{f&&n.results.results&&n.results.results.some((e=>e.isChosen))&&p(!1)}),[f,n.results.results]),(0,i.d4)((()=>{C>0&&setTimeout((()=>b(C-1)),1e3);const e=S.current;if(e){const t=12*Math.PI,n=e.lastElementChild,a=e.firstElementChild;if(C<=5&&e.classList.add("hurry-up"),n&&a){const e=(h.closePeriod-C)/h.closePeriod*t;a.textContent=(0,L.k9)(C),n.firstElementChild.setAttribute("stroke-dashoffset",`-${e}`)}else e.innerHTML=`\n ${(0,L.k9)(C)}\n \n \n `}}),[C,h.closePeriod]),(0,i.d4)((()=>{h.quiz&&(C<=0||k&&!h.closed)&&l({chatId:m,messageId:u})}),[m,C,k,l,u,h.closed,h.quiz]),(0,i.d4)((()=>{let e;return h.quiz&&!h.closed&&h.closePeriod&&h.closePeriod>0&&(e=window.setTimeout((()=>{l({chatId:m,messageId:u})}),1e3*h.closePeriod)),()=>{e&&window.clearTimeout(e)}}),[R,m,l,u,h.closePeriod,h.closed,h.quiz]);const O=(0,i.Ye)((()=>s?s.reduce(((e,t)=>{const n=o[t];return n&&e.push(n),e}),[]):[]),[o,s]),U=(0,i.I4)((e=>{I([e]),p(!0),P(!0),r([e])}),[r]),F=(0,i.I4)((e=>{I(e)}),[]),D=(0,i.I4)((()=>{p(!0),P(!0),r(v)}),[r,v]),$=(0,i.I4)((()=>{d({chatId:m,messageId:u})}),[m,u,d]),q=(0,i.I4)((()=>{w(!0)}),[]),j=(0,i.I4)((()=>{w(!1),P(!1)}),[]);(0,i.d4)((()=>{Z&&k&&h.quiz&&g.results&&n.results.solution&&(g.results.find((e=>e.isChosen&&e.isCorrect))||w(!0))}),[k,Z,g.results,h.quiz,n.results.solution]);const G=(0,Fe.Z)();return i.ZP.createElement("div",{className:"Poll",dir:G.isRtl?"auto":"ltr"},y&&n.results.solution&&i.ZP.createElement(wa.Z,{message:(0,va.H)(n.results.solution,n.results.solutionEntities),duration:5e3,onDismiss:j,containerId:"#middle-column-portals"}),i.ZP.createElement("div",{className:"poll-question"},(0,nn.Z)(h.question,["emoji","br"])),i.ZP.createElement("div",{className:"poll-type"},G(function(e){return void 0===e.isPublic?" ":e.quiz?e.isPublic?"QuizPoll":"AnonymousQuizPoll":e.closed?"FinalResults":e.isPublic?"PublicPoll":"AnonymousPoll"}(h)),O.length>0&&i.ZP.createElement("div",{className:"poll-recent-voters"},O.map((e=>i.ZP.createElement(rn.Z,{size:"micro",user:e})))),C>0&&R&&i.ZP.createElement("div",{ref:S,className:"poll-countdown"}),h.quiz&&n.results.solution&&!R&&i.ZP.createElement(ze.Z,{round:!0,size:"tiny",color:"translucent",className:"poll-quiz-help",disabled:y,onClick:q,ariaLabel:"Show Solution"},i.ZP.createElement("i",{className:"icon-lamp"}))),R&&i.ZP.createElement("div",{className:"poll-answers"},T?i.ZP.createElement(Ia.Z,{options:x,onChange:F,disabled:t.isScheduled||f,loadingOptions:f?v:void 0,round:!0}):i.ZP.createElement(ya.Z,{name:`poll-${u}`,options:x,onChange:U,disabled:t.isScheduled||f,loadingOption:f?v[0]:void 0})),!R&&i.ZP.createElement("div",{className:"poll-results"},h.answers.map((function(e){return i.ZP.createElement(Pa,{key:e.option,shouldAnimate:Z,answer:e,voteResults:E,totalVoters:M,maxVotersCount:B,correctResults:A})}))),!N&&!T&&i.ZP.createElement("div",{className:"poll-voters-count"},function(e,t,n){return n?e(t?"Answer":"Vote",n,"i"):e(t?"Chat.Quiz.TotalVotesEmpty":"Chat.Poll.TotalVotesResultEmpty")}(G,h.quiz,g.totalVoters)),T&&i.ZP.createElement(ze.Z,{isText:!0,disabled:0===v.length,size:"tiny",onClick:D},G("PollSubmitVotes")),N&&i.ZP.createElement(ze.Z,{isText:!0,size:"tiny",onClick:$},G("PollViewResults")))})));var ba=n(8035),Sa=n(88);const Ea=(0,i.X$)((e=>{let{message:t,observeIntersection:n,noAvatars:a,canAutoLoad:s,canAutoPlay:o,inPreview:r,lastSyncTime:c,isDownloading:l=!1,isProtected:u,theme:m,onMediaClick:h,onCancelMediaTransfer:g}=e;const f=(0,d.s1)(t);let p=!1;if(null!=f&&f.photo&&!f.video){const{width:e,height:n}=kn(t);p=e===n}const v=(0,i.I4)((()=>{h()}),[h]);if(!f)return;const{siteName:I,url:y,displayUrl:w,title:Z,description:P,photo:C,video:b}=f,S=(C||b)&&h&&!p,E=(0,ba.Z)(P,170),M=(0,fe.Z)("WebPage",p&&"with-square-photo",!C&&!b&&!r&&"without-media",b&&"with-video");return i.ZP.createElement("div",{className:M,"data-initial":(I||w)[0],dir:"auto"},C&&!b&&i.ZP.createElement(la,{message:t,observeIntersection:n,noAvatars:a,canAutoLoad:s,size:p?"pictogram":"inline",nonInteractive:!S,onClick:S?v:void 0,onCancelUpload:g,isDownloading:l,isProtected:u,theme:m}),i.ZP.createElement("div",{className:"WebPage-text"},i.ZP.createElement(Sa.Z,{className:"site-name",url:y,text:I||w}),!r&&Z&&i.ZP.createElement("p",{className:"site-title"},(0,nn.Z)(Z)),E&&i.ZP.createElement("p",{className:"site-description"},(0,nn.Z)(E,["emoji","br"]))),!r&&b&&i.ZP.createElement(ga,{message:t,observeIntersection:n,noAvatars:a,canAutoLoad:s,canAutoPlay:o,lastSyncTime:c,onClick:S?v:void 0,onCancelUpload:g,isDownloading:l,isProtected:u}))}));var Ma=n(9937);const ka=(0,i.X$)((e=>{let{message:t}=e;const n=(0,Fe.Z)(),a=(0,d.eO)(t),{title:s,text:o,amount:r,currency:c,isTest:l,photoUrl:u}=a;return i.ZP.createElement("div",{className:"Invoice"},s&&i.ZP.createElement("p",{className:"title"},(0,nn.Z)(s)),o&&i.ZP.createElement("p",null,(0,nn.Z)(o,["emoji","br"])),i.ZP.createElement("div",{className:"description "+(u?"has-image":"")},u&&i.ZP.createElement("img",{className:"invoice-image",src:u,alt:""}),i.ZP.createElement("p",{className:"description-text"},(0,Ma.x)(r,c,n.code),l&&i.ZP.createElement("span",null,n("PaymentTestInvoice")))))}));var Ra=n(8183);const Na=new Map(Object.entries({"building/medical":"#43b3f4","building/gym":"#43b3f4","education/cafeteria":"#f7943f","travel/bedandbreakfast":"#9987ff","travel/hotel":"#9987ff","travel/hostel":"#9987ff","travel/resort":"#9987ff","travel/hotel_bar":"#e56dd6",arts_entertainment:"#e56dd6",building:"#6e81b2",education:"#a57348",event:"#959595",food:"#f7943f",home:"#00aeef",nightlife:"#e56dd6",parks_outdoors:"#6cc039",shops:"#ffb300",travel:"#1c9fff",work:"#ad7854"})),Ta=["#e56cd5","#f89440","#9986ff","#44b3f5","#6dc139","#ff5d5a","#f87aad","#6e82b3","#f5ba21"],Ba=e=>{let{variant:t="rectangular",animation:n="wave",width:a,height:s,className:o}=e;const r=(0,fe.Z)("Skeleton",t,n,o),c=(a?`width: ${a}px;`:"")+(s?`height: ${s}px;`:"");return i.ZP.createElement("div",{className:r,style:c})};var Aa=n(8226);const xa=1e-4,La={width:400,height:300,zoom:16,scale:2},Oa={__html:''},Ua=(0,i.X$)((e=>{let{message:t,peer:n,lastSyncTime:a,isInSelectMode:o,isSelected:r,theme:c,serverTimeOffset:l}=e;const u=(0,i.sO)(null),m=(0,i.sO)(null),h=(0,Fe.Z)(),g=(0,kt.Z)(),p=(0,d.nf)(t),{type:v,geo:I}=p,y=(0,f.b)(l),w=(0,d.$R)(t,y),Z="geoLive"!==v||w?void 0:t.date+p.period-y,[P,C]=(0,i.eJ)(I),b="venue"===v||"geoLive"===v&&!w,{width:S,height:E,zoom:M,scale:k}=La,R=Boolean(a)&&(0,d.k6)(P,S,E,M,k),N=(0,Ut.Z)(R),T=(0,Mt.Z)(N),B=N||T,A=n&&(0,d.YC)(n.id),x=n&&A?n:void 0,O=n&&!A?n:void 0,U=(0,d.B4)(t),F=(0,i.Ye)((()=>{if("geoLive"!==v||!P.accuracyRadius)return 0;const{lat:e,accuracyRadius:t}=P;return t/function(e,t){return 156543.03392*Math.cos(e*(Math.PI/180))/2**t}(e,M)}),[v,P,M]),D=(0,i.I4)((e=>{if("geoLive"!==v)return;const n=24*Math.PI,a=e.lastElementChild,s=e.firstElementChild,i=t.date+p.period-(0,f.b)(l),o=(1-i/p.period)*n,r=(0,L.mB)(h,1e3*i);a&&s?(s.textContent=r,a.firstElementChild.setAttribute("stroke-dashoffset",`-${o}`)):e.innerHTML=`\n ${r}\n \n \n `}),[v,t.date,p,l,h]);return(0,i.bt)((()=>{m.current&&D(m.current)}),[D]),(0,i.bt)((()=>{if(b)return;const e=u.current.closest(".message-content");B&&ra(B,U,0,r,c).then((t=>{e.style.setProperty("--appendix-bg",t),e.classList.add("has-appendix-thumb"),e.setAttribute(s.s2,"")}))}),[U,o,r,c,B,b]),(0,i.d4)((()=>{Math.abs(I.lat-P.lat){g()}),w?void 0:1e3*(Z||0)),(0,wn.Z)((()=>{const e=m.current;e&&D(e)}),Z?1e3:void 0),i.ZP.createElement("div",{ref:u,className:"Location media-inner interactive",onClick:()=>{var e;const t=function(e,t,n){return`http://maps.google.com/maps/place/${e}+${t}/@${e},${t},${n}z`}(P.lat,P.long,M);null===(e=window.open(t,"_blank"))||void 0===e||e.focus()}},i.ZP.createElement("div",{className:"map-wrapper"},B?i.ZP.createElement("img",{className:"full-media map",src:B,alt:"Location on a map",width:La.width,height:La.height}):i.ZP.createElement(Ba,{width:S,height:E}),function(){if(B)return i.ZP.createElement(i.ZP.Fragment,null,Boolean(F)&&!w&&i.ZP.createElement("div",{className:"location-accuracy",style:`width: ${2*F}px; height: ${2*F}px`}),function(){const e=(0,fe.Z)("pin",v,w&&"expired");if("geoLive"===v)return i.ZP.createElement("div",{className:e,dangerouslySetInnerHTML:Oa},i.ZP.createElement(rn.Z,{chat:O,user:x,className:"location-avatar"}),void 0!==p.heading&&i.ZP.createElement("div",{className:"direction",style:`--direction: ${p.heading}deg`}));if("venue"===v){const t=function(e){return e?Na.get(e)||Na.get(e.split("/")[0])||Ta[(t=e,t.split("").reduce(((e,t)=>(e<<5)-e+t.charCodeAt(0)|0),0)%Ta.length)]:"#008df2";var t}(p.venueType),n=function(e){return e?`https://ss3.4sqi.net/img/categories_v2/${e}_88.png`:""}(p.venueType);return i.ZP.createElement("div",{className:e,dangerouslySetInnerHTML:Oa,style:`--pin-color: ${t}`},i.ZP.createElement("img",{src:n,className:"venue-icon",alt:""}))}return i.ZP.createElement("img",{className:e,src:Aa,alt:""})}())}()),function(){if(b)return"venue"===v?i.ZP.createElement("div",{className:"location-info"},i.ZP.createElement("div",{className:"location-info-title"},p.title),i.ZP.createElement("div",{className:"location-info-subtitle"},p.address)):"geoLive"===v?i.ZP.createElement("div",{className:"location-info"},i.ZP.createElement("div",{className:"location-info-title"},h("AttachLiveLocation")),i.ZP.createElement("div",{className:"location-info-subtitle"},(0,L.dJ)(h,y,t.editDate)),!w&&i.ZP.createElement("div",{className:"geo-countdown",ref:m})):void 0}())}));function Fa(e){return(0,i.X$)((0,a.c$)(((e,t)=>{const{message:n}=t;return{isInSelectMode:(0,c.CA)(e),isSelected:(0,c.vk)(e,n.id)}}))((t=>{const{isInSelectMode:n,isSelected:s,message:o,dimensions:r}=t,{toggleMessageSelection:c}=(0,a.Sv)(),l=(0,i.I4)((e=>{e.stopPropagation(),c({messageId:o.id,withShift:null==e?void 0:e.shiftKey})}),[c,o]),d=(0,i.Ye)((()=>{const{dimensions:e,onClick:a}=t;return{...t,isInSelectMode:n,isSelected:s,dimensions:{...e,x:0,y:0},onClick:n?void 0:a}}),[t,n,s]);return i.ZP.createElement("div",{className:(0,fe.Z)("album-item-select-wrapper",s&&"is-selected"),style:r?`left: ${r.x}px; top: ${r.y}px;`:"",onClick:n?l:void 0},n&&i.ZP.createElement("div",{className:"message-select-control"},s&&i.ZP.createElement("i",{className:"icon-select"})),i.ZP.createElement(e,d))})))}const Da=Fa(la),$a=Fa(ga),qa=(0,a.c$)(((e,t)=>{let{album:n}=t;const{chatId:a}=n.mainMessage,s=(0,c.Pu)(e),i=(0,c.xs)(e,a);return{theme:s,uploadsById:e.fileUploads.byMessageLocalId,activeDownloadIds:i}}))((e=>{let{album:t,observeIntersection:n,hasCustomAppendix:s,lastSyncTime:o,isOwn:r,isProtected:l,albumLayout:u,onMediaClick:m,uploadsById:h,activeDownloadIds:g,theme:f}=e;const{cancelSendingMessage:p}=(0,a.Sv)(),v=t.messages.length,I=(0,i.I4)((e=>{p({chatId:e.chatId,messageId:e.id})}),[p]),{width:y,height:w}=u.containerStyle;return i.ZP.createElement("div",{className:"Album",style:`width: ${y}px; height: ${w}px;`},t.messages.map((function(e,t){const{photo:p,video:y}=(0,d.qp)(e),w=h[e.previousLocalId||e.id],Z=null==w?void 0:w.progress,{dimensions:P,sides:C}=u.layout[t],b=(0,c.bH)((0,a.Rd)(),e),S=(0,c.__)((0,a.Rd)(),e);if(p){const a=s&&(r?t===v-1:Boolean(8&C&&4&C));return i.ZP.createElement(Da,{id:`album-media-${(0,d.d0)(e.id)}`,message:e,observeIntersection:n,canAutoLoad:b,shouldAffectAppendix:a,uploadProgress:Z,dimensions:P,isProtected:l,onClick:m,onCancelUpload:I,isDownloading:g.includes(e.id),theme:f})}if(y)return i.ZP.createElement($a,{id:`album-media-${(0,d.d0)(e.id)}`,message:e,observeIntersection:n,canAutoLoad:b,canAutoPlay:S,uploadProgress:Z,lastSyncTime:o,dimensions:P,isProtected:l,onClick:m,onCancelUpload:I,isDownloading:g.includes(e.id),theme:f})})))}));function ja(){return ja=Object.assign||function(e){for(var t=1;t{let{message:t,observeIntersection:n,canAutoLoad:s,lastSyncTime:r,isDownloading:c}=e;const l=(0,i.sO)(null),u=(0,i.sO)(null),m=(0,i.sO)(null),h=t.content.video,g=(0,Pn.Op)(l,n),[f,p]=(0,i.eJ)(s),v=Boolean(f&&g&&r),{mediaData:I,loadProgress:y}=(0,aa.Z)((0,d.Ti)(t,"inline"),!v,(0,d.kG)(t,"inline"),r),{loadProgress:w}=(0,aa.Z)((0,d.Ti)(t,"download"),!c,o.IU.BlobUrl,r),Z=ia(t,I),{isBuffered:P,bufferingHandlers:C}=(0,da.Z)(),b=f&&!P||c,S=!1===(0,Mt.Z)(f),M=(0,Qn.Z)(I),{shouldRender:k,transitionClassNames:R}=(0,ye.Z)(b||!P,void 0,S),[N,T]=(0,i.eJ)(!1),[B,A]=(0,i.eJ)(0);(0,i.d4)((()=>{if(!N)return;const e=Ot.Rj/2,t=2*(e-6)*Math.PI,n=t-B*t,a=m.current,s=u.current,i=s.firstElementChild;i?i.firstElementChild.setAttribute("stroke-dashoffset",n.toString()):s.innerHTML=`\n \n \n `,A(a.currentTime/a.duration)}),[N,B]);const x=Boolean(I&&g),O=(0,i.I4)((()=>{m.current&&(T(!1),A(0),(0,ea.Z)(m.current),(0,E.T2)((()=>{u.current.innerHTML=""})))}),[]),U=(0,i.I4)((()=>{var e;null===(e=Ga)||void 0===e||e(),Ga=O}),[O]);(0,i.d4)((()=>{m.current&&(x?(0,ea.Z)(m.current):m.current.pause())}),[x]),ma(m,x),(0,ua.Z)(m,[I]);const F=(0,i.I4)((()=>{if(!I)return void p((e=>!e));if(c)return void(0,a.Sv)().cancelMessageMediaDownload({message:t});const e=m.current;N?e.paused?((0,ea.Z)(e),(0,zt.Es)()):e.pause():(U(),e.pause(),e.currentTime=0,(0,ea.Z)(e),(0,zt.Es)(),T(!0))}),[U,N,c,I,t]),D=(0,i.I4)((e=>{const t=e.currentTarget;A(t.currentTime/t.duration)}),[]),$=(0,fe.Z)("full-media",M);return i.ZP.createElement("div",{ref:l,className:"RoundVideo media-inner",onClick:F},i.ZP.createElement("div",{className:"thumbnail-wrapper"},i.ZP.createElement("canvas",{ref:Z,className:"thumbnail",style:`width: ${Ot.Rj}px; height: ${Ot.Rj}px`})),I&&i.ZP.createElement("div",{className:"video-wrapper"},i.ZP.createElement("video",ja({ref:m,className:$,width:Ot.Rj,height:Ot.Rj,autoPlay:!0,muted:!N,loop:!N,playsInline:!0,onEnded:N?O:void 0},C,{onTimeUpdate:N?D:void 0}),i.ZP.createElement("source",{src:I}))),i.ZP.createElement("div",{className:"progress",ref:u}),k&&i.ZP.createElement("div",{className:`media-loading ${R}`},i.ZP.createElement(ca.Z,{progress:c?w:y})),!I&&!f&&i.ZP.createElement("i",{className:"icon-download"}),i.ZP.createElement("div",{className:"message-media-duration"},N?(0,L.k9)(m.current.currentTime):(0,L.k9)(h.duration),(!N||m.current.paused)&&i.ZP.createElement("i",{className:"icon-muted"})))},_a=e=>{let{message:t,onClick:n}=e;const a=(0,Fe.Z)();return i.ZP.createElement("div",{className:"InlineButtons"},t.inlineButtons.map((e=>i.ZP.createElement("div",{className:"row"},e.map((e=>i.ZP.createElement(ze.Z,{size:"tiny",ripple:!0,disabled:"NOT_SUPPORTED"===e.type,onClick:()=>n({button:e})},(0,nn.Z)(a(e.text)),"buy"===e.type&&i.ZP.createElement("i",{className:"icon-card"}),"url"===e.type&&!e.value.match(s.FS)&&i.ZP.createElement("i",{className:"icon-arrow-right"}))))))))},za=(0,i.X$)((e=>{let{threadInfo:t,disabled:n}=e;const{openChat:s}=(0,a.Sv)(),o=(0,Fe.Z)(),{threadId:r,chatId:c,messagesCount:l,lastMessageId:u,lastReadInboxMessageId:m,recentReplierIds:h}=t,g=(0,i.I4)((()=>{s({id:c,threadId:r})}),[s,c,r]),f=(0,i.Ye)((()=>{if(null==h||!h.length)return;const{users:{byId:e},chats:{byId:t}}=(0,a.Rd)();return h.map((n=>(0,d.YC)(n)?e[n]:t[n])).filter(Boolean)}),[h]);if(void 0===l)return;const p=Boolean(m&&u&&m0&&i.ZP.createElement("div",{className:"recent-repliers",dir:o.isRtl?"rtl":"ltr"},f.map((e=>i.ZP.createElement(rn.Z,{key:e.id,size:"small",user:(0,d.YC)(e.id)?e:void 0,chat:(0,d.YC)(e.id)?void 0:e})))),i.ZP.createElement("div",{className:"label",dir:"auto"},l?o("Comments",l,"i"):o("LeaveAComment")),i.ZP.createElement("i",{className:"icon-next"}))})),Va=(0,i.X$)((e=>{let{reaction:t,message:n,activeReaction:s,availableReactions:o}=e;const{sendReaction:r}=(0,a.Sv)(),{recentReactions:c}=n.reactions,l=(0,i.Ye)((()=>{if(!c||t.count>3)return;const e=(0,a.Rd)().users.byId;return c.filter((e=>e.reaction===t.reaction)).map((t=>e[t.userId])).filter(Boolean)}),[t,c]),d=(0,i.I4)((()=>{r({reaction:t.isChosen?void 0:t.reaction,chatId:n.chatId,messageId:n.id})}),[n,t,r]);return i.ZP.createElement(ze.Z,{className:(0,fe.Z)(t.isChosen&&"chosen"),size:"tiny",onClick:d},i.ZP.createElement(Yn,{activeReaction:s,reaction:t.reaction,availableReactions:o}),null!=l&&l.length?i.ZP.createElement("div",{className:"avatars"},l.map((e=>i.ZP.createElement(rn.Z,{user:e,size:"micro"})))):(0,Re.bi)(t.count))})),Xa=(0,i.X$)((e=>{let{message:t,isOutside:n,activeReaction:a,availableReactions:s,metaChildren:o}=e;return i.ZP.createElement("div",{className:(0,fe.Z)("Reactions",n&&"is-outside")},t.reactions.results.map((e=>i.ZP.createElement(Va,{key:e.reaction,reaction:e,message:t,activeReaction:a,availableReactions:s}))),o)}));var Ka=n(7324),Wa=n(5296);const Ya=(0,i.X$)((e=>{let{localSticker:t,localEffect:n,isOwn:a,soundId:s,size:o="medium",observeIntersection:r,messageId:c,chatId:l,activeEmojiInteractions:d}=e;const{playKey:u,ref:m,style:h,width:g,handleClick:f,markAnimationLoaded:p}=(0,Wa.Z)(o,l,c,s,d,a,n),v=`local_emoji_${t}`,I=(0,Pn.Op)(m,r),[y,w]=(0,i.eJ)();return(0,i.d4)((()=>{t&&(0,Ka.Z)(t).then((e=>{w(e)}))}),[t]),i.ZP.createElement("div",{ref:m,className:"AnimatedEmoji media-inner",style:h,onClick:f},y&&i.ZP.createElement(Wn.Z,{key:v,id:v,animationData:y,size:g,quality:1,play:I&&u,forceOnHeavyAnimation:!0,noLoop:!0,onLoad:p}))})),Ja={__html:''},Qa={__html:''},es=(0,i.X$)((0,a.c$)(((e,t)=>{const{focusedMessage:n,forwardMessages:a,lastSyncTime:s,serverTimeOffset:i}=e,{message:o,album:r,withSenderName:l,withAvatar:u,threadId:m,messageListType:h,isLastInDocumentGroup:g}=t,{id:f,chatId:p,viaBotId:v,replyToChatId:I,replyToMessageId:y,isOutgoing:w,threadInfo:Z}=o,P=(0,c.Z1)(e,p),C=(0,c.FM)(e,p),b=(0,d.pK)(p),S=P&&(0,d.eA)(P),E=null==P?void 0:P.username,M=!C&&(0,d.Ul)(o),k=l||u||M,R=(0,c.Ur)(e,o),N=(0,c.cv)(e,o),T=v?(0,c.dy)(e,v):void 0,B=m?(0,c.qS)(e,p,m):void 0,A=o.id===B,x=y===B,L=y&&!x?(0,c.hj)(e,b&&I?I:p,y):void 0,O=L&&(0,c.Ur)(e,L),U=(0,c.uZ)(e,o),F="thread"===h&&(r?r.messages.some((t=>(0,c._X)(e,t))):(0,c._X)(e,o)),{direction:D,noHighlight:$,isResizingContainer:q}=F&&n||{},j=a.messageIds&&a.messageIds.includes(f),{query:G}=(0,c.n5)(e)||{},H=(0,d._O)(o);let _;_=null!=r&&r.messages?r.messages.every((t=>{let{id:n}=t;return(0,c.vk)(e,n)})):(0,c.vk)(e,f);const{canReply:z}="thread"===h&&(0,c._k)(e,o,m)||{},V=(0,c.te)(e,o),X=Z?(0,c.tZ)(e,Z.chatId,Z.threadId)||Z:void 0,K=Boolean(o.groupedId)&&!o.isInAlbum,W=K?(0,c.xH)(e,p,o.groupedId)[0]:void 0,Y=K?g?(0,c.hj)(e,p,W):void 0:o,J=H?(0,c.CP)(e,H):void 0;return{theme:(0,c.Pu)(e),chatUsername:E,forceSenderName:M,sender:R,canShowSender:k,originSender:N,botSender:T,shouldHideReply:x,isThreadTop:A,replyMessage:L,replyMessageSender:O,isInDocumentGroup:K,isProtected:(0,c.EV)(e,o),isFocused:F,isForwarding:j,reactionMessage:Y,isChatWithSelf:C,isRepliesChat:b,isChannel:S,canReply:z,lastSyncTime:s,serverTimeOffset:i,highlight:G,isSingleEmoji:Boolean(H),animatedEmoji:H?(0,c.zB)(e,H):void 0,animatedEmojiEffect:H&&(0,d.YC)(p)?(0,c.tH)(e,H):void 0,animatedEmojiSoundId:H?(0,c.Oh)(e,H):void 0,localSticker:J,localEffect:J&&(0,d.YC)(p)?(0,c.cu)(J):void 0,isInSelectMode:(0,c.CA)(e),isSelected:_,isGroupSelected:Boolean(o.groupedId)&&!o.isInAlbum&&(0,c.a6)(e,p,o.groupedId),threadId:m,isDownloading:V,isPinnedList:"pinned"===h,canAutoLoadMedia:(0,c.bH)(e,o),canAutoPlayMedia:(0,c.__)(e,o),autoLoadFileMaxSizeMb:e.settings.byKey.autoLoadFileMaxSizeMb,shouldLoopStickers:(0,c.yB)(e),threadInfo:X,availableReactions:e.availableReactions,defaultReaction:(0,d.CI)(o)?void 0:(0,c.q6)(e,p),activeReaction:Y&&e.activeReactions[Y.id],activeEmojiInteractions:e.activeEmojiInteractions,...w&&{outgoingStatus:(0,c.dT)(e,o,"scheduled"===h)},..."number"==typeof U&&{uploadProgress:U},...F&&{focusDirection:D,noFocusHighlight:$,isResizingContainer:q}}}))((e=>{let{message:t,chatUsername:n,observeIntersectionForBottom:s,observeIntersectionForMedia:r,observeIntersectionForAnimatedStickers:c,album:l,noAvatars:u,withAvatar:g,withSenderName:p,areReactionsInMeta:v,noComments:I,appearanceOrder:y,isFirstInGroup:w,isLastInGroup:Z,isFirstInDocumentGroup:P,isLastInDocumentGroup:C,isLastInList:b,theme:S,forceSenderName:E,sender:M,canShowSender:k,originSender:R,botSender:N,isThreadTop:T,shouldHideReply:B,replyMessage:A,replyMessageSender:x,outgoingStatus:L,uploadProgress:O,isInDocumentGroup:U,isProtected:F,isFocused:D,focusDirection:$,noFocusHighlight:q,isResizingContainer:j,isForwarding:G,isChatWithSelf:H,isRepliesChat:_,isChannel:z,canReply:V,lastSyncTime:X,serverTimeOffset:K,highlight:W,animatedEmoji:Y,localSticker:J,localEffect:Q,animatedEmojiEffect:ee,animatedEmojiSoundId:te,isInSelectMode:ne,isSelected:ae,isGroupSelected:se,threadId:ie,reactionMessage:oe,availableReactions:re,defaultReaction:ce,activeReaction:le,activeEmojiInteractions:de,messageListType:ue,isPinnedList:me,isDownloading:he,canAutoLoadMedia:ge,canAutoPlayMedia:pe,shouldLoopStickers:ve,autoLoadFileMaxSizeMb:Ie,threadInfo:we}=e;const{toggleMessageSelection:Ze,clickInlineButton:Pe,disableContextMenuHint:Ce}=(0,a.Sv)(),be=(0,i.sO)(null),Se=(0,i.sO)(null),Ee=(0,i.sO)(null),Me=(0,Fe.Z)();(0,Pn._N)(Se,s);const{isContextMenuOpen:ke,contextMenuPosition:Re,handleBeforeContextMenu:Ne,handleContextMenu:Te,handleContextMenuClose:Be,handleContextMenuHide:Ae}=(0,Sn.Z)(be,h.$b&&ne,!0,h.wZ);(0,i.d4)((()=>{ke&&Ce()}),[ke,Ce]);const xe=y<=0,[Le,Ue]=(0,Oe.Z)(xe);(0,i.d4)((()=>{xe||setTimeout(Ue,10*y)}),[y,Ue,xe]);const{transitionClassNames:De}=(0,ye.Z)(Le,void 0,xe,!1),{id:$e,chatId:qe,forwardInfo:je,viaBotId:Ge}=t,He=(0,d.CI)(t),_e=(0,d.B4)(t),Ve="scheduled"===ue||t.isScheduled,Xe=(0,d.ss)(t)&&!B,Ke=Boolean(we)&&"thread"===ue,We=(0,d.$D)(t),Ye=J||Y,Je=(null==oe?void 0:oe.reactions)&&!(0,d.JE)(oe.reactions),Qe=je&&(!H||Ve)&&!_&&!je.isLinkedChannelPost&&!We,et=Boolean(l)&&l.messages.length>1,tt=U&&!P,nt=U&&!C,at=void 0!==Re,st=!(at||ne||G||nt),it=z&&!Ve,ot=Boolean(me||je&&(je.isChannelPost||H&&!_e||_)&&je.fromMessageId),rt=we&&!nt&&"thread"===ue&&!I,ct=!h.$b&&!ne&&ce&&!nt,lt=(0,i.I4)(((e,t)=>{Ze({messageId:$e,groupedId:t,...(null==e?void 0:e.shiftKey)&&{withShift:!0},...et&&{childMessageIds:l.messages.map((e=>{let{id:t}=e;return t}))}})}),[Ze,$e,et,l]),dt=k?M:void 0,ut=je&&(H||_||!dt)?R:dt,mt=je?R:dt,{handleMouseDown:ht,handleClick:gt,handleContextMenu:ft,handleDoubleClick:pt,handleContentDoubleClick:vt,handleMouseMove:It,handleSendQuickReaction:yt,handleMouseLeave:wt,isSwiped:Zt,isQuickReactionVisible:Pt,handleDocumentGroupMouseEnter:Ct}=Dn(lt,be,$e,0,Boolean(ne),Boolean(V),Boolean(F),Te,Ne,qe,at,Ee,_e,nt),{handleAvatarClick:bt,handleSenderClick:St,handleViaBotClick:Et,handleReplyClick:Mt,handleMediaClick:kt,handleAudioPlay:Rt,handleAlbumMediaClick:Tt,handleMetaClick:Bt,handleReadMedia:At,handleCancelUpload:xt,handleVoteSend:Lt,handleGroupForward:Ut,handleForward:Ft,handleFocus:Dt,handleFocusForwarded:$t,handleDocumentGroupSelectAll:qt}=function(e,t,n,s,r,c,l,d,u,h,g,f,p){const{openChat:v,showNotification:I,focusMessage:y,openMediaViewer:w,openAudioPlayer:Z,markMessagesRead:P,cancelSendingMessage:C,sendPollVote:b,openForwardMenu:S,focusMessageInComments:E}=(0,a.Sv)(),{id:M,forwardInfo:k,replyToMessageId:R,replyToChatId:N,replyToTopMessageId:T,groupedId:B}=n,A=(0,i.I4)((()=>{g&&v({id:g.id})}),[g,v]),x=(0,i.I4)((()=>{f?l&&null!=k&&k.channelPostId?y({chatId:f.id,messageId:k.channelPostId}):v({id:f.id}):I({message:e("HidAccount")})}),[l,y,k,e,v,f,I]),L=(0,i.I4)((()=>{p&&v({id:p.id})}),[p,v]),O=(0,i.I4)((()=>{y({chatId:u&&N?N:s,threadId:r,messageId:R,replyMessageId:u&&N?void 0:M})}),[y,u,N,s,r,R,M]),U=(0,i.I4)((()=>{w({chatId:s,threadId:r,messageId:M,origin:d?m.bZ.ScheduledInline:m.bZ.Inline})}),[s,r,M,w,d]),F=(0,i.I4)((()=>{Z({chatId:s,messageId:M})}),[s,M,Z]),D=(0,i.I4)((e=>{w({chatId:s,threadId:r,messageId:e,origin:d?m.bZ.ScheduledAlbum:m.bZ.Album})}),[s,r,w,d]),$=(0,i.I4)((()=>{P({messageIds:[M]})}),[M,P]),q=(0,i.I4)((()=>{C({chatId:s,messageId:M})}),[C,s,M]),j=(0,i.I4)((e=>{b({chatId:s,messageId:M,options:e})}),[s,M,b]),G=(0,i.I4)((()=>{S({fromChatId:s,groupedId:B})}),[S,s,B]),H=(0,i.I4)((()=>{if(h&&h.messages){const e=h.messages.map((e=>{let{id:t}=e;return t}));S({fromChatId:s,messageIds:e})}else S({fromChatId:s,messageIds:[M]})}),[h,S,s,M]),_=(0,i.I4)((()=>{y({chatId:s,threadId:o._f,messageId:M})}),[y,s,M]),z=(0,i.I4)((()=>{c?y({chatId:k.fromChatId,groupedId:B,groupedChatId:s}):u&&N?E({chatId:N,threadId:T,messageId:k.fromMessageId}):y({chatId:k.fromChatId,messageId:k.fromMessageId})}),[c,u,N,y,k,B,s,E,T]),V=(0,i.I4)((e=>{e.stopPropagation(),t(e,B)}),[t,B]);return{handleAvatarClick:A,handleSenderClick:x,handleViaBotClick:L,handleReplyClick:O,handleMediaClick:U,handleAudioPlay:F,handleAlbumMediaClick:D,handleMetaClick:V,handleReadMedia:$,handleCancelUpload:q,handleVoteSend:j,handleGroupForward:G,handleForward:H,handleFocus:_,handleFocusForwarded:z,handleDocumentGroupSelectAll:V}}(Me,lt,t,qe,ie,U,Qe,Ve,_,l,ut,mt,N),Gt=(0,fe.Z)("Message message-list-item",w&&"first-in-group",F&&"is-protected",Z&&"last-in-group",P&&"first-in-document-group",C&&"last-in-document-group",b&&"last-in-list",_e&&"own",Boolean(t.views)&&"has-views",t.isEdited&&"was-edited",Xe&&"has-reply",at&&"has-menu-open",D&&!q&&"focused",G&&"is-forwarding",t.isDeleting&&"is-deleting",U&&"is-in-document-group",et&&"is-album",t.hasUnreadMention&&"has-unread-mention",ae&&"is-selected",ne&&"is-in-selection-mode",T&&"is-thread-top",Boolean(t.inlineButtons)&&"has-inline-buttons",Zt&&"is-swiped",De,Boolean(le)&&"has-active-reaction"),{text:Ht,photo:_t,video:zt,audio:Vt,voice:Xt,document:Kt,sticker:Wt,contact:Yt,poll:Jt,webPage:Qt,invoice:en,location:tn}=(0,d.qp)(t),an=function(e){let{hasReply:t,customShape:n,isLastInGroup:a,asForwarded:s,hasThread:i,forceSenderName:o,hasComments:r,hasActionButton:c,hasReactions:l,isGeoLiveActive:u}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{text:m,photo:h,video:g,audio:f,voice:p,document:v,poll:I,webPage:y,contact:w,location:Z}=(0,d.qp)(e),P=["message-content"],C=h||g||Z,b=m||"venue"===(null==Z?void 0:Z.type)||u,S=C&&!b,E=Boolean(e.viaBotId);return En(n)?P.push(`emoji-only emoji-only-${n}`):b&&P.push("text"),c&&P.push("has-action-button"),n&&(P.push("custom-shape"),null!=g&&g.isRound&&P.push("round"),r&&P.push("has-comments")),C?P.push("media"):f?P.push("audio"):p?P.push("voice"):v?P.push("document"):w?P.push("contact"):I?P.push("poll"):y&&(P.push("web-page"),(y.photo||y.video)&&P.push("media")),s&&P.push("is-forwarded"),t&&P.push("is-reply"),i&&P.push("has-replies"),l&&P.push("has-reactions"),E&&P.push("is-via-bot"),o&&P.push("force-sender-name"),n||(P.push("has-shadow"),C&&r&&P.push("has-background"),(t||s||!S||E||o)&&P.push("has-solid-background"),a&&(h||Z&&!b||!S)&&P.push("has-appendix")),P.join(" ")}(t,{hasReply:Xe,customShape:We,isLastInGroup:Z,asForwarded:Qe,hasThread:Ke,forceSenderName:E,hasComments:we&&(null==we?void 0:we.messagesCount)>0,hasActionButton:it||ot,hasReactions:Je,isGeoLiveActive:"geoLive"===(null==tn?void 0:tn.type)&&!(0,d.$R)(t,(0,f.b)(K))}),sn=an.includes("has-appendix"),on=(0,jt.X)(t,W,En(We));let cn,ln;cn=nt?"none":!on||Ye||Qt?"standalone":"in-text",v?ln="in-meta":Je?We||(_t||zt||Ye)&&!on?ln="outside":Qe?(cn="standalone",ln="inside"):ln="inside":ln="none",(0,Nt.Z)(_&&t.replyToChatId?t.replyToChatId:qe,Xe?t.replyToMessageId:void 0,A,t.id),Ln(be,qe,D,$,q,j);let dn,un="",mn=!1;const hn=(0,i.Ye)((()=>et?Bn(_e,Boolean(Qe),Boolean(u),l):void 0),[et,_e,Qe,u,l]),gn=Qe?28:0;if(et||!_t&&!zt)hn&&(dn=Math.max(Mn(Boolean(Ht),rt),hn.containerStyle.width),dn-hn.containerStyle.width>18&&(mn=!0));else{let e;_t?e=kn(t,u).width:zt&&(e=zt.isRound?Ot.Rj:kn(t,u).width),e&&(dn=Math.max(Mn(Boolean(Ht),rt),e),dn-e>18&&(mn=!0))}dn&&(un=`width: ${dn+gn}px`);const fn=z&&t.adminTitle||!Qe&&(null==je?void 0:je.adminTitle)||void 0,pn=(0,i.Ye)((()=>fn?xn(fn):void 0),[fn]);function vn(){const e=i.ZP.createElement(Jn,{message:t,reactionMessage:oe,outgoingStatus:L,signature:fn,withReactions:"in-meta"===ln,withReactionOffset:"inside"===ln,availableReactions:re,activeReaction:le,onClick:Bt});return"inside"!==ln?e:i.ZP.createElement(Xa,{activeReaction:le,message:oe,metaChildren:e,availableReactions:re})}return i.ZP.createElement("div",{ref:be,id:(0,d.d0)(t.id),className:Gt,style:pn?`--meta-safe-author-width: ${pn}px`:void 0,"data-message-id":$e,onMouseDown:ht,onClick:gt,onContextMenu:ft,onDoubleClick:pt,onMouseEnter:nt?Ct:void 0,onMouseMove:ct?It:void 0,onMouseLeave:ct||nt?wt:void 0},i.ZP.createElement("div",{ref:Se,className:"bottom-marker","data-message-id":$e,"data-last-message-id":l?l.messages[l.messages.length-1].id:void 0,"data-has-unread-mention":t.hasUnreadMention}),!U&&i.ZP.createElement("div",{className:"message-select-control"},ae&&i.ZP.createElement("i",{className:"icon-select"})),C&&i.ZP.createElement("div",{className:(0,fe.Z)("message-select-control group-select",se&&"is-selected"),onClick:qt},se&&i.ZP.createElement("i",{className:"icon-select"})),g&&function(){const e=ut&&(0,d.YC)(ut.id),t=ut&&e?ut:void 0,n=ut&&!e?ut:void 0,a=!ut&&je?je.hiddenUserName:void 0;return i.ZP.createElement(rn.Z,{size:"small",user:t,chat:n,text:a,lastSyncTime:X,onClick:t||n?bt:void 0})}(),i.ZP.createElement("div",{className:(0,fe.Z)("message-content-wrapper",an.includes("text")&&"can-select-text")},i.ZP.createElement("div",{ref:Ee,className:an,style:un,dir:"auto"},Qe&&!tt&&i.ZP.createElement("div",{className:"message-title"},Me("ForwardedMessage")),function(){const e=(0,fe.Z)("content-inner",Qe&&"forwarded-message",Xe&&"reply-message",mn&&"no-media-corners"),n=Z&&!on&&!Qe&&!Ke,a=(0,fe.Z)("text-content","in-text"===cn&&"with-meta",L&&"with-outgoing-icon");return i.ZP.createElement("div",{className:e,onDoubleClick:vt,dir:"auto"},function(){if(We&&!Ge||!(p&&!(_t||zt||tn)||Qe||Ge||E)||tt||Xe&&We)return;let e,n;return!mt||We&&Ge?null!=je&&je.hiddenUserName&&(e=je.hiddenUserName):(e=(0,d.OU)(Me,mt),Qe||(n=`color-${(0,d.Rs)(mt)}`)),i.ZP.createElement("div",{className:"message-title",dir:"ltr"},e?i.ZP.createElement("span",{className:(0,fe.Z)("interactive",n),onClick:St,dir:"auto"},(0,nn.Z)(e)):N?void 0:" ",N&&i.ZP.createElement(i.ZP.Fragment,null,i.ZP.createElement("span",{className:"via"},Me("ViaBot")),i.ZP.createElement("span",{className:"interactive",onClick:Et},(0,nn.Z)(`@${N.username}`))),null!=je&&je.isLinkedChannelPost?i.ZP.createElement("span",{className:"admin-title",dir:"auto"},Me("DiscussChannel")):t.adminTitle&&!z?i.ZP.createElement("span",{className:"admin-title",dir:"auto"},t.adminTitle):void 0)}(),Xe&&i.ZP.createElement(_n,{message:A,isProtected:F,sender:x,observeIntersection:r,onClick:Mt}),Wt&&i.ZP.createElement(ta,{message:t,observeIntersection:r,observeIntersectionForPlaying:c,shouldLoop:ve,lastSyncTime:X}),Y&&i.ZP.createElement(na.Z,{size:"small",isOwn:_e,sticker:Y,effect:ee,soundId:te,observeIntersection:r,lastSyncTime:X,forceLoadPreview:He,messageId:$e,chatId:qe,activeEmojiInteractions:de}),J&&i.ZP.createElement(Ya,{size:"small",isOwn:_e,localSticker:J,localEffect:Q,soundId:te,observeIntersection:r,lastSyncTime:X,forceLoadPreview:He,messageId:$e,chatId:qe,activeEmojiInteractions:de}),et&&i.ZP.createElement(qa,{album:l,albumLayout:hn,observeIntersection:r,isOwn:_e,isProtected:F,hasCustomAppendix:n,lastSyncTime:X,onMediaClick:Tt}),!et&&_t&&i.ZP.createElement(la,{message:t,observeIntersection:r,noAvatars:u,canAutoLoad:ge,uploadProgress:O,shouldAffectAppendix:n,onClick:kt,onCancelUpload:xt,isDownloading:he,isProtected:F,theme:S}),!et&&zt&&zt.isRound&&i.ZP.createElement(Ha,{message:t,observeIntersection:r,canAutoLoad:ge,lastSyncTime:X,isDownloading:he}),!et&&zt&&!zt.isRound&&i.ZP.createElement(ga,{message:t,observeIntersection:r,noAvatars:u,canAutoLoad:ge,canAutoPlay:pe,uploadProgress:O,lastSyncTime:X,onClick:kt,onCancelUpload:xt,isDownloading:he,isProtected:F}),(Vt||Xt)&&i.ZP.createElement(Vn.Z,{theme:S,message:t,origin:m.Cr.Inline,uploadProgress:O,lastSyncTime:X,isSelectable:U,isSelected:ae,onPlay:Rt,onReadMedia:!Xt||_e&&!H?void 0:At,onCancelUpload:xt,isDownloading:he}),Kt&&i.ZP.createElement(zn.Z,{message:t,observeIntersection:r,canAutoLoad:ge,autoLoadFileMaxSizeMb:Ie,uploadProgress:O,isSelectable:U,isSelected:ae,onMediaClick:kt,onCancelUpload:xt,isDownloading:he}),Yt&&i.ZP.createElement(pa,{contact:Yt}),Jt&&i.ZP.createElement(Ca,{message:t,poll:Jt,onSendVote:Lt}),!Ye&&on&&i.ZP.createElement("p",{className:a,dir:"auto"},on,"in-text"===cn&&vn()),Qt&&i.ZP.createElement(Ea,{message:t,observeIntersection:r,noAvatars:u,canAutoLoad:ge,canAutoPlay:pe,lastSyncTime:X,onMediaClick:kt,onCancelMediaTransfer:xt,isDownloading:he,isProtected:F,theme:S}),en&&i.ZP.createElement(ka,{message:t}),tn&&i.ZP.createElement(Ua,{message:t,lastSyncTime:X,isInSelectMode:ne,isSelected:ae,theme:S,peer:M,serverTimeOffset:K}))}(),!nt&&"standalone"===cn&&vn(),st&&it?i.ZP.createElement(ze.Z,{className:"message-action-button",color:"translucent-white",round:!0,size:"tiny",ariaLabel:Me("lng_context_forward_msg"),onClick:C?Ut:Ft},i.ZP.createElement("i",{className:"icon-share-filled"})):st&&ot?i.ZP.createElement(ze.Z,{className:"message-action-button",color:"translucent-white",round:!0,size:"tiny",ariaLabel:"Focus message",onClick:me?Dt:$t},i.ZP.createElement("i",{className:"icon-arrow-right"})):void 0,rt&&i.ZP.createElement(za,{threadInfo:we,disabled:I}),sn&&i.ZP.createElement("div",{className:"svg-appendix",dangerouslySetInnerHTML:_e?Ja:Qa}),ct&&i.ZP.createElement("div",{className:(0,fe.Z)("quick-reaction",Pt&&!le&&"visible"),onClick:yt},i.ZP.createElement(Kn.Z,{reaction:ce}))),t.inlineButtons&&i.ZP.createElement(_a,{message:t,onClick:Pe}),"outside"===ln&&i.ZP.createElement(Xa,{message:oe,isOutside:!0,activeReaction:le,availableReactions:re})),Re&&i.ZP.createElement(Gn,{isOpen:ke,anchor:Re,message:t,album:l,chatUsername:n,messageListType:ue,onClose:Be,onCloseAnimationEnd:Ae}))}))),ts=(0,i.X$)((0,a.c$)(((e,t)=>{let{chatId:n}=t;const a=(0,c.fS)(e,n),{chatId:s,isBot:i}=a||{};return{message:a,bot:s&&i?(0,c.dy)(e,s):void 0,channel:!i&&s?(0,c.Z1)(e,s):void 0}}))((e=>{let{chatId:t,message:n,containerRef:s,bot:o,channel:r}=e;const{viewSponsoredMessage:c,openChat:l,openChatByInvite:u,startBot:m,focusMessage:h}=(0,a.Sv)(),g=(0,Fe.Z)(),f=(0,i.sO)(null),p=Boolean(n),{observe:v}=(0,Pn.S1)({rootRef:s,debounceMs:200,threshold:1});if((0,i.d4)((()=>p?v(f.current,(e=>{e.isIntersecting&&c({chatId:t})})):void 0),[t,p,v,c]),n)return i.ZP.createElement("div",{className:"SponsoredMessage Message open",key:"sponsored-message"},i.ZP.createElement("div",{className:"message-content has-shadow has-solid-background",dir:"auto"},i.ZP.createElement("div",{className:"content-inner",dir:"auto"},i.ZP.createElement("div",{className:"message-title",dir:"ltr"},o&&(0,nn.Z)((0,d.Js)(o)||""),r&&(0,nn.Z)(n.chatInviteTitle||(0,d.U)(g,r,o)||"")),i.ZP.createElement("p",{className:"text-content with-meta",dir:"auto",ref:f},i.ZP.createElement("span",{className:"text-content-inner",dir:"auto"},(0,va.H)(n.text.text,n.text.entities)),i.ZP.createElement("span",{className:"MessageMeta",dir:"ltr"},i.ZP.createElement("span",{className:"message-signature"},g("SponsoredMessage")))),i.ZP.createElement(ze.Z,{color:"secondary",size:"tiny",ripple:!0,onClick:()=>{n.chatInviteHash?u({hash:n.chatInviteHash}):n.channelPostId?h({chatId:n.chatId,messageId:n.channelPostId}):(l({id:n.chatId}),n.startParam&&m({botId:n.chatId,param:n.startParam}))},className:"SponsoredMessage__button"},g(n.isBot?"Conversation.ViewBot":n.channelPostId?"Conversation.ViewPost":"Conversation.ViewChannel")))))}))),ns=(0,i.X$)((e=>{let{chatId:t,messageIds:n,messageGroups:o,isViewportNewest:r,isUnread:c,withUsers:l,areReactionsInMeta:u,noAvatars:f,containerRef:p,anchorIdRef:v,memoUnreadDividerBeforeIdRef:I,memoFirstUnreadIdRef:y,threadId:w,type:Z,isReady:P,isScrollingRef:C,isScrollPatchNeededRef:b,threadTopMessageId:S,hasLinkedChat:M,isSchedule:k,noAppearanceAnimation:R,onFabToggle:N,onNotchToggle:T}=e;const{openHistoryCalendar:B}=(0,a.Sv)(),{observeIntersectionForMedia:A,observeIntersectionForReading:x,observeIntersectionForAnimatedStickers:O}=function(e,t,n){const{markMessageListRead:s,markMessagesRead:i}=(0,a.Sv)(),{observe:o}=(0,Pn.S1)({rootRef:t,throttleMs:Cn,margin:bn}),{observe:r,freeze:c,unfreeze:l}=(0,Pn.S1)({rootRef:t,throttleMs:150},(t=>{if("thread"!==e)return;let a=0;const o=[];t.forEach((e=>{const{isIntersecting:t,target:n}=e;if(!t)return;const{dataset:s}=n,i=Number(s.lastMessageId||s.messageId);i>a&&(a=i),s.hasUnreadMention&&o.push(i)})),n.current&&a>=n.current&&s({maxId:a}),o.length&&i({messageIds:o})}));(0,we.Z)(c,l);const{observe:d}=(0,Pn.S1)({rootRef:t,throttleMs:Cn});return{observeIntersectionForMedia:o,observeIntersectionForReading:r,observeIntersectionForAnimatedStickers:d}}(Z,p,y),{backwardsTriggerRef:U,forwardsTriggerRef:F,fabTriggerRef:D}=function(e,t,n,o,r,c,l,d,u,g){const{loadViewportMessages:f}=(0,a.Sv)(),[p,v]=(0,i.Ye)((()=>"thread"===e?[(0,E.Ds)((()=>f({direction:m.Uq.Backwards})),1e3,!0,!1),(0,E.Ds)((()=>f({direction:m.Uq.Forwards})),1e3,!0,!1)]:[]),[f,n]),I=(0,i.sO)(null),y=(0,i.sO)(null),w=(0,i.sO)(null);function Z(){if(!d)return;if(!n||!n.length)return c(!1),void l(!1);if(!o)return c(!0),void l(!0);if(!t.current)return;const{offsetHeight:e,scrollHeight:a,scrollTop:s}=t.current,i=Math.round(a-s-e),u=i<=1;c(r?!u:!(i<=50)),l(!u)}const{observe:P}=(0,Pn.S1)({rootRef:t,margin:h.gZ},(e=>{if(!v||!p)return;if(n[0]>=s.AE)return;const t=e.find((e=>{let{isIntersecting:t}=e;return t}));if(!t)return;const{target:a}=t;"backwards-trigger"===a.className?(h.i4&&u.current&&n.length<=s.hT&&(g.current=!0),p()):"forwards-trigger"===a.className&&v()}));(0,Pn._N)(I,P),(0,Pn._N)(y,P);const{observe:C,freeze:b,unfreeze:S}=(0,Pn.S1)({rootRef:t,margin:100},Z);(0,Pn._N)(w,C);const{observe:M,freeze:k,unfreeze:R}=(0,Pn.S1)({rootRef:t,margin:1},Z);return(0,Pn._N)(w,M),(0,Pe.Z)((()=>{d&&Z()}),[d]),(0,Pe.Z)((()=>{b(),k(),setTimeout((()=>{R(),S()}),250)}),[n]),{backwardsTriggerRef:I,forwardsTriggerRef:y,fabTriggerRef:w}}(Z,p,n,r,c,N,T,P,C,b),$=(0,Fe.Z)(),q=i.ZP.createElement("div",{className:(0,fe.Z)("unread-divider","local-action-message"),key:"unread-messages"},i.ZP.createElement("span",null,$("UnreadMessages"))),j=R?0:o.reduce(((e,t)=>e+(0,g.xH)(t.senderGroups).length),0);let G=0;const H=o.map(((e,t,n)=>{const a=e.senderGroups.map(((e,a,s)=>{if(1===e.length&&!gn(e[0])&&(0,d.Lo)(e[0])){const o=e[0],r=a===s.length-1&&t===n.length-1;return(0,g.oA)([o.id===I.current&&q,i.ZP.createElement(Hn,{key:o.id,message:o,observeIntersection:x,appearanceOrder:j-++G,isLastInList:r})])}let o;return(0,g.xH)(e.map(((r,c)=>{const m=gn(r)?r.mainMessage:r,h=gn(r)?r:void 0,p=(0,d.B4)(m),y=gn(r),P=e[c+1];m.previousLocalId&&v.current===(0,d.d0)(m.previousLocalId)&&(v.current=(0,d.d0)(m.id));const C=!y&&m.groupedId?m.groupedId:void 0,b=P&&!gn(P)?P.groupedId:void 0,E={isFirstInGroup:0===c,isLastInGroup:c===e.length-1,isFirstInDocumentGroup:Boolean(C&&C!==o),isLastInDocumentGroup:Boolean(C&&C!==b),isLastInList:c===e.length-1&&a===s.length-1&&t===n.length-1};o=C;const k=(0,d.KK)(m),R="scheduled"!==Z?k:`${m.date}_${k}`;return(0,g.oA)([m.id===I.current&&q,i.ZP.createElement(es,{key:R,message:m,observeIntersectionForBottom:x,observeIntersectionForMedia:A,observeIntersectionForAnimatedStickers:O,album:h,noAvatars:f,withAvatar:E.isLastInGroup&&l&&!p&&!(m.id===S),withSenderName:E.isFirstInGroup&&l&&!p,areReactionsInMeta:u,threadId:w,messageListType:Z,noComments:!1===M,appearanceOrder:j-++G,isFirstInGroup:E.isFirstInGroup,isLastInGroup:E.isLastInGroup,isFirstInDocumentGroup:E.isFirstInDocumentGroup,isLastInDocumentGroup:E.isLastInDocumentGroup,isLastInList:E.isLastInList}),m.id===S&&i.ZP.createElement("div",{className:"local-action-message",key:"discussion-started"},i.ZP.createElement("span",null,$("DiscussionStarted")))])})))}));return i.ZP.createElement("div",{className:"message-date-group",key:e.datetime,onMouseDown:pn.q,teactFastList:!0},i.ZP.createElement("div",{className:(0,fe.Z)("sticky-date",!k&&"interactive"),key:"date-header",onMouseDown:pn.q,onClick:k?void 0:()=>B({selectedAt:e.datetime})},i.ZP.createElement("span",{dir:"auto"},k&&e.originalDate===s.t4&&$("MessageScheduledUntilOnline"),k&&e.originalDate!==s.t4&&$("MessageScheduledOn",(0,L.j1)($,e.datetime,void 0,!0)),!k&&(0,L.j1)($,e.datetime))),(0,g.xH)(a))}));return i.ZP.createElement("div",{className:"messages-container",teactFastList:!0},i.ZP.createElement("div",{ref:U,key:"backwards-trigger",className:"backwards-trigger"}),(0,g.xH)(H),r&&i.ZP.createElement(ts,{key:t,chatId:t,containerRef:p}),i.ZP.createElement("div",{ref:F,key:"forwards-trigger",className:"forwards-trigger"}),i.ZP.createElement("div",{ref:D,key:"fab-trigger",className:"fab-trigger"}))}));var as=n(3547);const ss=(0,i.X$)((0,a.c$)(((e,t)=>{let{userId:n}=t;const{stickers:a}=e.stickers.greeting,s=(0,d.db)(n)+(0,d.db)(e.currentUserId),i=null!=a&&a.length?a[s%a.length]:void 0,o=(0,c.Z1)(e,n);return o?{sticker:i,lastUnreadMessageId:o.lastMessage&&o.lastMessage.id!==o.lastReadInboxMessageId?o.lastMessage.id:void 0,connectionState:e.connectionState}:{}}))((e=>{let{sticker:t,connectionState:n,lastUnreadMessageId:s}=e;const{loadGreetingStickers:o,sendMessage:r,markMessageListRead:c}=(0,a.Sv)(),l=(0,Fe.Z)(),d=(0,i.sO)(null),{observe:u}=(0,Pn.S1)({rootRef:d,debounceMs:200});(0,i.d4)((()=>{t||"connectionStateReady"!==n||o()}),[n,o,t]),(0,i.d4)((()=>{"connectionStateReady"===n&&s&&c({maxId:s})}),[n,c,s]);const m=(0,i.I4)((e=>{e={...e,isPreloadedGlobally:!0},r({sticker:e})}),[r]);return i.ZP.createElement("div",{className:"ContactGreeting",ref:d},i.ZP.createElement("div",{className:"wrapper"},i.ZP.createElement("p",{className:"title",dir:"auto"},l("Conversation.EmptyPlaceholder")),i.ZP.createElement("p",{className:"description",dir:"auto"},l("Conversation.GreetingText")),i.ZP.createElement("div",{className:"sticker"},t&&i.ZP.createElement(as.Z,{sticker:t,onClick:m,clickArg:t,observeIntersection:u,size:160,className:"large",noContextMenu:!0}))))}))),is=(0,i.X$)((e=>{let{isChatWithSelf:t,type:n,isGroupChatJustCreated:a}=e;const s=(0,Fe.Z)();return"scheduled"===n?function(e){return i.ZP.createElement("div",{className:"empty"},i.ZP.createElement("span",null,e("ScheduledMessages.EmptyPlaceholder")))}(s):t?function(e){return i.ZP.createElement("div",{className:"NoMessages"},i.ZP.createElement("div",{className:"wrapper"},i.ZP.createElement("i",{className:"icon icon-cloud-download"}),i.ZP.createElement("h3",{className:"title"},e("Conversation.CloudStorageInfo.Title")),i.ZP.createElement("ul",{className:"description"},i.ZP.createElement("li",null,e("Conversation.ClousStorageInfo.Description1")),i.ZP.createElement("li",null,e("Conversation.ClousStorageInfo.Description2")),i.ZP.createElement("li",null,e("Conversation.ClousStorageInfo.Description3")),i.ZP.createElement("li",null,e("Conversation.ClousStorageInfo.Description4")))))}(s):a?function(e){return i.ZP.createElement("div",{className:"NoMessages"},i.ZP.createElement("div",{className:"wrapper",dir:e.isRtl?"rtl":void 0},i.ZP.createElement("h3",{className:"title"},e("EmptyGroupInfo.Title")),i.ZP.createElement("p",{className:"description"},e("EmptyGroupInfo.Subtitle")),i.ZP.createElement("ul",{className:"list-checkmarks"},i.ZP.createElement("li",null,e("EmptyGroupInfo.Line1")),i.ZP.createElement("li",null,e("EmptyGroupInfo.Line2")),i.ZP.createElement("li",null,e("EmptyGroupInfo.Line3")),i.ZP.createElement("li",null,e("EmptyGroupInfo.Line4")))))}(s):i.ZP.createElement("div",{className:"empty"},i.ZP.createElement("span",null,s("NoMessages")))})),os=(0,E.Ds)((e=>e()),200,!1),rs=(0,i.X$)((0,a.c$)(((e,t)=>{let{chatId:n,threadId:a,type:s}=t;const i=(0,c.Z1)(e,n);if(!i)return{};const r=(0,c.$W)(e,n,a,s),l="scheduled"===s?(0,c.Fn)(e,n):(0,c.Zw)(e,n),u=(0,c.qS)(e,n,a);if(a!==o._f&&!(l&&u&&l[u]))return{};const{isRestricted:m,restrictionReason:h,lastMessage:g}=i,f=(0,c.G$)(e,n),p=a===o._f&&!r&&!i.unreadCount&&!f&&g&&!g.groupedId,v=(0,c.IK)(e,n);let I;return(0,c.pk)(e,n)&&(I=v.fullInfo?v.fullInfo.botDescription||"NoMessages":"Updating bot info..."),{isChatLoaded:!0,isRestricted:m,restrictionReason:h,isChannelChat:(0,d.eA)(i),isGroupChat:(0,d.Bf)(i),isCreator:i.isCreator,isChatWithSelf:(0,c.FM)(e,n),isRepliesChat:(0,d.pK)(n),isBot:Boolean(v),messageIds:r,messagesById:l,firstUnreadId:(0,c.It)(e,n,a),isViewportNewest:"thread"!==s||(0,c.b9)(e,n,a),threadFirstMessageId:(0,c.yZ)(e,n,a),focusingId:f,isSelectModeActive:(0,c.CA)(e),botDescription:I,threadTopMessageId:u,hasLinkedChat:i.fullInfo&&"linkedChatId"in i.fullInfo?Boolean(i.fullInfo.linkedChatId):void 0,lastSyncTime:e.lastSyncTime,...p&&{lastMessage:g}}}))((e=>{var t,n,o,r,l,u;let{chatId:f,threadId:p,type:v,hasTools:I,onFabToggle:y,onNotchToggle:w,isChatLoaded:Z,isChannelChat:P,isGroupChat:C,canPost:b,isReady:S,isChatWithSelf:M,isRepliesChat:k,isCreator:R,isBot:N,messageIds:T,messagesById:B,firstUnreadId:A,isViewportNewest:x,threadFirstMessageId:L,isRestricted:O,restrictionReason:U,focusingId:F,isSelectModeActive:D,lastMessage:$,botDescription:q,threadTopMessageId:j,hasLinkedChat:G,lastSyncTime:H,withBottomShift:_}=e;const{loadViewportMessages:z,setScrollOffset:V,loadSponsoredMessages:X,loadMessageReactions:K,copyMessagesByIds:W}=(0,a.Sv)(),Y=(0,i.sO)(null),J=(0,i.sO)("thread"===v&&(0,c.Vt)((0,a.Rd)(),f,p)||0),Q=(0,i.sO)(),ee=(0,i.sO)(),te=(0,i.sO)(),ne=(0,i.sO)(),ae=(0,i.sO)(),se=(0,i.sO)(),ie=(0,i.sO)(!1),oe=(0,i.sO)(Boolean($)),[re,ce]=(0,i.eJ)(),le=Boolean(T);(0,Pe.Z)((()=>{le&&(0,E.R3)((()=>{oe.current=!1}))}),[le]),(0,Pe.Z)((()=>{ne.current=A}),[A]),(0,Pe.Z)((()=>{P&&S&&H&&X({chatId:f})}),[f,S,P,H]),(0,Pe.Z)((()=>{le&&(ae.current=ne.current)}),[le]),(0,Pe.Z)((()=>{se.current=F}),[F]),(e=>{(0,i.d4)((()=>{function t(t){if((h.jm&&t.metaKey||!h.jm&&t.ctrlKey)&&"c"===(0,xe.Z)(t)){const n=(0,Zn.Z)();n&&n.length>0&&(t.preventDefault(),e({messageIds:n}))}}return document.addEventListener("keydown",t,!1),()=>{document.removeEventListener("keydown",t,!1)}}),[e])})(W);const de=(0,i.Ye)((()=>{if(!T||!B)return;const e=!j||T[0]&&L!==T[0]?T:[j,...T];if(!e.length)return;const t=e.map((e=>B[e])).filter(Boolean);return fn((0,g.Xo)(t,["date","id"]),ae.current)}),[T,B,L,j]);(0,wn.Z)((()=>{if(!T||!B)return;const e=T.filter((e=>{var t;return null===(t=B[e])||void 0===t?void 0:t.reactions}));e.length&&K({chatId:f,ids:e})}),15e3);const ue=(0,i.Ye)((()=>{if("thread"===v)return(0,E.Ds)((()=>z({direction:m.Uq.Around})),1e3,!0,!1)}),[z,T]),{isScrolled:me,updateStickyDates:he}=function(){const[e,t]=(0,Oe.Z)(!1),n=(0,vn.Z)(1e3,!0);return{isScrolled:e,updateStickyDates:(0,i.I4)(((e,a)=>{t(),document.body.classList.contains("is-scrolling-messages")||(0,E.T2)((()=>{document.body.classList.add("is-scrolling-messages")})),n((()=>{(0,E.T2)((()=>{const t=document.querySelector(".stuck");t&&t.classList.remove("stuck");const n=function(e,t){const n=e.querySelectorAll(".sticky-date"),a=e.scrollTop;return Array.from(n).find((e=>{const{offsetTop:n,offsetHeight:s}=e,i=n-a;return-s<=i&&i<=(t?60:10)}))}(e,a);n&&n.classList.add("stuck"),document.body.classList.remove("is-scrolling-messages")}))}))}),[t,n])}}(),pe=(0,i.sO)(),ve=(0,i.sO)(),Ie=(0,i.I4)((()=>{if(ie.current)return void(ie.current=!1);pe.current=!0;const e=Y.current;se.current||he(e,I),os((()=>{pe.current=!1,(0,E.T2)((()=>{e.parentElement&&(J.current=e.scrollHeight-e.scrollTop,"thread"===v&&V({chatId:f,threadId:p,scrollOffset:J.current}))}))}))}),[he,I,v,V,f,p]);(0,i.d4)((()=>{if(!("ResizeObserver"in window))return;const e=new ResizeObserver((e=>{let[t]=e;t.target.offsetParent&&ce(t.contentRect.height)}));return e.observe(Y.current),()=>{e.disconnect()}}),[]);const{height:ye}=St();(0,i.d4)((()=>{Y.current.dataset.normalHeight=String(Y.current.offsetHeight)}),[ye,b]),(0,i.d4)((()=>{if(!ue||!Z||O||F)return;if(T&&T[T.length-1]>=s.AE)return;const e=Y.current;(!T||T.length{if(!T||!te.current)return;const e=te.current.filter((e=>T.includes(Number(e.dataset.messageId)))),t=e[1]||e[0];t&&(Q.current=t.id,ee.current=t.getBoundingClientRect().top)}),[T,x,re,I]),(0,mn.Z)((e=>{let[t,n,a]=e;const i=Y.current;te.current=Array.from(i.querySelectorAll(".message-list-item"));const o=T&&t&&T[T.length-1]!==t[t.length-1],r=(null==T?void 0:T[0])!==(null==t?void 0:t[0])&&(null==T?void 0:T.length)===s.hT/2+1,c=o&&!r,l=T&&se.current===T[T.length-1],d=x&&c&&T&&T.length{i.parentElement&&i.parentElement.classList.remove("force-messages-scroll")}),500));const{scrollTop:u,scrollHeight:m,offsetHeight:h}=i,g=J.current,f=te.current[te.current.length-1];let p=g-(a||h);c&&(p-=f?f.offsetHeight:0);const v=x&&n&&p<=20;let y;if(c&&v&&!l&&(f&&(0,E.T2)((()=>{(0,yn.Z)(i,f,"end",20)})),y=m-h,J.current=Math.max(Math.ceil(m-y),h),!d))return;const w=void 0!==a&&a!==re,Z=Q.current&&i.querySelector(`#${Q.current}`),P=!Z&&ae.current&&i.querySelector(".unread-divider");if(v&&w){if((0,yn.N)())return;y=m-h}else Z?(ve.current&&(ve.current=!1,(0,In.z)(i)),y=u+(Z.getBoundingClientRect().top-(ee.current||0))):y=P?Math.min(P.offsetTop-(I?60:10),m-g):m-g;(0,In.Z)(i,Math.ceil(y)),se.current||(ie.current=!0,(0,E.T2)((()=>{ie.current=!1}))),J.current=Math.max(Math.ceil(m-y),h)}),[T,x,re,I]),(0,hn.Z)((e=>{let[t]=e;void 0!==t&&(0,ge.YW)(200+s.fK)}),[D]);const we=(0,Fe.Z)(),Ze=Boolean(f&&(0,d.YC)(f)),Ce=Boolean(!Ze&&!P||M||k),be=Boolean(!Ce||P),Se=(0,d.YC)(f)&&!M&&!N&&(!de&&!$&&T&&(!te.current||0===te.current.length)||1===(null==T?void 0:T.length)&&"contactSignUp"===(null==B||null===(t=B[T[0]])||void 0===t||null===(n=t.content.action)||void 0===n?void 0:n.type)||"contactSignUp"===(null==$||null===(o=$.content)||void 0===o||null===(r=o.action)||void 0===r?void 0:r.type)),Ee=C&&R&&1===(null==T?void 0:T.length)&&"chatCreate"===(null==B||null===(l=B[T[0]])||void 0===l||null===(u=l.content.action)||void 0===u?void 0:u.type),Me=(0,fe.Z)("MessageList custom-scroll",be&&"no-avatars",!b&&"no-composer","pinned"===v&&"type-pinned",_&&"with-bottom-shift",D&&"select-mode-active",me&&"scrolled",!S&&"is-animating");return i.ZP.createElement("div",{ref:Y,className:Me,onScroll:Ie,onMouseDown:pn.q},O?i.ZP.createElement("div",{className:"empty"},i.ZP.createElement("span",null,U?U.text:"This is a private "+(P?"channel":"chat"))):q?i.ZP.createElement("div",{className:"empty"},i.ZP.createElement("span",null,(0,nn.Z)(we(q),["br","emoji","links"]))):Se?i.ZP.createElement(ss,{userId:f}):!T||de&&!Ee?T&&de||$?i.ZP.createElement(ns,{chatId:f,messageIds:T||[$.id],messageGroups:de||fn([$]),isViewportNewest:Boolean(x),isUnread:Boolean(A),withUsers:Ce,areReactionsInMeta:Ze,noAvatars:be,containerRef:Y,anchorIdRef:Q,memoUnreadDividerBeforeIdRef:ae,memoFirstUnreadIdRef:ne,threadId:p,type:v,isReady:S,isScrollingRef:pe,isScrollPatchNeededRef:ve,threadTopMessageId:j,hasLinkedChat:G,isSchedule:!!de&&"scheduled"===v,noAppearanceAnimation:!de||!oe.current,onFabToggle:y,onNotchToggle:w}):i.ZP.createElement(rt.Z,{color:"white",backgroundColor:"dark"}):i.ZP.createElement(is,{chatId:f,type:v,isChatWithSelf:M,isGroupChatJustCreated:Ee}))}))),cs=(0,i.X$)((0,a.c$)((e=>{const t=(0,c.Bt)(e);if(!t)return{};const{chatId:n,threadId:a,type:s}=t,i=(0,c.Z1)(e,n);return{messageListType:s,unreadCount:i&&a===o._f&&"thread"===s?i.unreadCount:void 0}}))((e=>{let{isShown:t,canPost:n,messageListType:s,unreadCount:o,withExtraShift:r}=e;const{focusNextReply:c}=(0,a.Sv)(),l=(0,Fe.Z)(),d=(0,i.sO)(null),u=(0,i.I4)((()=>{if(t)if("thread"===s)c();else{const e=d.current.parentElement.querySelector(".MessageList"),t=e.querySelectorAll(".message-list-item"),n=t[t.length-1];if(!n)return;(0,yn.Z)(e,n,"end",20)}}),[t,s,c]),m=(0,fe.Z)("ScrollDownButton",t&&"revealed",!n&&"no-composer",r&&"with-extra-shift");return i.ZP.createElement("div",{ref:d,className:m},i.ZP.createElement("div",{className:"ScrollDownButton-inner"},i.ZP.createElement(ze.Z,{color:"secondary",round:!0,onClick:u,ariaLabel:l("AccDescrPageDown")},i.ZP.createElement("i",{className:"icon-arrow-down"})),Boolean(o)&&i.ZP.createElement("div",{className:"unread-count"},(0,Re.bi)(o))))})));var ls=n(5723);const ds=1280,us=/\.[^/.]+$/;async function ms(e,t,n,a){const i=URL.createObjectURL(t),{type:o,size:r}=t;let c,l;if(s.oG.has(o))if(n){const t=await(0,bt.pt)(i),{width:n,height:s}=t;if(n>ds||s>ds||"image/jpeg"!==o){const t=await Kt(i,ds/Math.max(n,s),"image/jpeg");return URL.revokeObjectURL(i),ms(e,await(0,bt.gm)(t),!0,a)}"image/jpeg"===o&&(e=e.replace(us,".jpg")),c={width:n,height:s}}else l=i;else if(s.wG.has(o)){const{videoWidth:e,videoHeight:t,duration:n}=await(0,bt.jj)(i);c={width:e,height:t,duration:n},l=await(0,bt.ud)(i)}return{blobUrl:i,filename:e,mimeType:o,size:r,quick:c,previewBlobUrl:l,...a}}function hs(e){const t=window.getSelection();if(null!=t&&t.getRangeAt&&t.rangeCount){const n=t.getRangeAt(0);n.deleteContents();const a=n.createContextualFragment(e),s=a.lastChild;n.insertNode(a),s?(n.setStartAfter(s),n.setEndAfter(s)):n.collapse(!1),t.removeAllRanges(),t.addRange(n)}}var gs=n(6391);let fs;function ps(e){fs.focus(),e.focus()}h.cj&&(fs=document.createElement("input"),fs.classList.add("for-ios-autocapitalization-fix"),document.body.appendChild(fs));var vs=n(4784),Is=n(2400),ys=n(6389),ws=n(971);const Zs={encoderPath:new URL(n(8973),n.b).href,reuseWorker:!0},Ps={type:"audio/ogg"};let Cs,bs,Ss;async function Es(){return Cs||(Cs=n.e(161).then(n.t.bind(n,1161,23)),bs=(await Cs).default,Ss=new bs(Zs)),Cs}async function Ms(e){await async function(){await Es(),await Ss.start()}();const t=Date.now();let n;const a=[],s=[];Ss.ondataavailable=e=>{a.push(e)};const i=function(t,n){const a=t.sourceNode,i=a.context.createAnalyser();i.fftSize=64,a.connect(i);const o=i.frequencyBinCount,r=new Uint8Array(o);let c=!1;return function t(){if(c)return;i.getByteFrequencyData(r);const n=r.reduce(((e,t)=>e+t),0)/o/255;(t=>{s.push(255*t),e(t)})(n<.1?0:n),requestAnimationFrame(t)}(),()=>{c=!0}}(Ss);return{stop:()=>new Promise(((e,o)=>{Ss.onstop=()=>{e({blob:new Blob(a,Ps),duration:Math.round(((n||Date.now())-t)/1e3),waveform:s})},Ss.onerror=o;const r=Math.max(0,t+1e3-Date.now());setTimeout((()=>{Ss.stop(),i()}),r)})),pause:()=>{const e=Math.max(0,t+1e3-Date.now());setTimeout((()=>{Ss.pause(),n=Date.now(),i()}),e)}}}var ks=n(1262);const Rs=["image/png","image/jpeg","image/gif"];let Ns,Ts;var Bs=n(3575),As=n(9295);function xs(e,t,n){const a=(0,vn.Z)(t,!0),[s,o]=(0,i.eJ)(),[r,c,l]=(0,Oe.Z)();return(0,ge.ZP)(c,l),(0,Pe.Z)((()=>{r||a((()=>{o(e())}))}),[...n,r]),s}const Ls=/^@([a-z0-9_]{1,32})[\u00A0\u0020]+(.*)/i,Os=/^@([a-z0-9_]{1,32})[\u00A0\u0020]+\n{2,}/i,Us={username:"",query:"",canShowHelp:!1,usernameLowered:""},Fs=document.createElement("div");const Ds=(0,E.P2)((e=>e()),500,!0),$s=/^[\w@]{1,32}\s?/i;var qs=n(3057);const js=(0,i.X$)((e=>{const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"DeleteMessageModal",!t);return n?i.ZP.createElement(n,e):void 0}));function Gs(){return Gs=Object.assign||function(e){for(var t=1;t{let{onActivate:t,...n}=e;const a=(0,i.sO)(!1),s=(0,i.I4)((()=>{if(a.current=!0,_s)return _s=!1,void t();Hs&&(clearTimeout(Hs),Hs=void 0),Hs=window.setTimeout((()=>{a.current&&t()}),200)}),[t]),o=(0,i.I4)((()=>{a.current=!1}),[]);return i.ZP.createElement(ze.Z,Gs({},n,{onMouseEnter:h.$b?void 0:s,onMouseLeave:h.$b?void 0:o,onClick:t}))}));var Vs=n(5655),Xs=n(6503);const Ks=(0,i.X$)((e=>{let{isButtonVisible:t,canAttachMedia:n,canAttachPolls:a,onFileSelect:o,onPollCreate:r}=e;const[c,l,d]=(0,Oe.Z)(),[u,m,g]=(0,Xs.Z)(c,d);(0,i.d4)((()=>{c&&g()}),[c,g]);const f=(0,i.I4)(((e,t)=>{const{files:n}=e.target;n&&n.length>0&&o(Array.from(n),t)}),[o]),p=(0,i.I4)((()=>{(0,Vs.g)(Array.from(s.dI).join(","),(e=>f(e,!0)))}),[f]),v=(0,i.I4)((()=>{(0,Vs.g)("*",(e=>f(e,!1)))}),[f]),I=(0,Fe.Z)();if(t)return i.ZP.createElement("div",{className:"AttachMenu"},i.ZP.createElement(zs,{id:"attach-menu-button",className:c?"AttachMenu--button activated":"AttachMenu--button",round:!0,color:"translucent",onActivate:l,ariaLabel:"Add an attachment",ariaControls:"attach-menu-controls",hasPopup:!0},i.ZP.createElement("i",{className:"icon-attach"})),i.ZP.createElement(dt.Z,{id:"attach-menu-controls",isOpen:c,autoClose:!0,positionX:"right",positionY:"bottom",onClose:d,className:"AttachMenu--menu fluid",onCloseAnimationEnd:d,onMouseEnter:h.$b?void 0:u,onMouseLeave:h.$b?void 0:m,noCloseOnBackdrop:!h.$b,ariaLabelledBy:"attach-menu-button"},!n&&i.ZP.createElement(_e.Z,{className:"media-disabled",disabled:!0},"Posting media content is not allowed in this group."),n&&i.ZP.createElement(i.ZP.Fragment,null,i.ZP.createElement(_e.Z,{icon:"photo",onClick:p},I("AttachmentMenu.PhotoOrVideo")),i.ZP.createElement(_e.Z,{icon:"document",onClick:v},I("AttachDocument"))),a&&i.ZP.createElement(_e.Z,{icon:"poll",onClick:r},I("Poll"))))})),Ws=(0,i.X$)((e=>{const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"SymbolMenu",!t);return n?i.ZP.createElement(n,e):void 0})),Ys=(0,i.X$)((e=>{const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"InlineBotTooltip",!t);return n?i.ZP.createElement(n,e):void 0})),Js=(0,i.X$)((e=>{const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"MentionTooltip",!t);return n?i.ZP.createElement(n,e):void 0}));var Qs=n(7146);const ei=(0,i.X$)((e=>{const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"StickerTooltip",!t);return n?i.ZP.createElement(n,e):void 0}));var ti=n(9830);const ni=(0,i.X$)((e=>{const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"BotCommandTooltip",!t);return n?i.ZP.createElement(n,e):void 0})),ai=(0,i.X$)((0,a.c$)(((e,t)=>{let{messageId:n}=t;const{chatId:a}=(0,c.Bt)(e)||{};return a?{message:(0,c.hj)(e,a,n)}:{}}))((e=>{let{isOpen:t,message:n,onClose:s}=e;const{clickInlineButton:o}=(0,a.Sv)(),[r,c]=(0,Xs.Z)(t,s),{isKeyboardSingleUse:l}=n||{},[d,u,m]=(0,Oe.Z)(!0),g=()=>{m(),s()};if((0,i.d4)((()=>{u()}),[u,null==n?void 0:n.keyboardButtons]),n&&n.keyboardButtons)return i.ZP.createElement(dt.Z,{isOpen:t||d,autoClose:l,positionX:"right",positionY:"bottom",onClose:g,className:"BotKeyboardMenu",onCloseAnimationEnd:g,onMouseEnter:h.$b?void 0:r,onMouseLeave:h.$b?void 0:c,noCompact:!0},i.ZP.createElement("div",{className:"content"},n.keyboardButtons.map((e=>i.ZP.createElement("div",{className:"row"},e.map((e=>i.ZP.createElement(ze.Z,{ripple:!0,disabled:"NOT_SUPPORTED"===e.type,onClick:()=>o({button:e})},e.text))))))))})));var si=n(3616),ii=n(7891);const oi=(0,i.X$)((0,a.c$)((e=>{const{chatId:t,threadId:n,type:a}=(0,c.Bt)(e)||{};if(!t||!n||!a)return{};const{currentUserId:s,forwardMessages:{fromChatId:i,toChatId:o,messageIds:r}}=e,l=(0,c.Yy)(e,t,n),u="scheduled"===a?(0,c.wU)(e,t):(0,c._$)(e,t,n),m=e.settings.byKey.animationLevel>=1,h=o===t;let g,f;if(l?g=(0,c.hj)(e,t,l):u?g=(0,c.kK)(e,t,n,a):h&&1===r.length&&(g=(0,c.hj)(e,i,r[0])),l&&g){const{forwardInfo:n}=g,a=t===s;n&&(n.isChannelPost||a)&&(f=(0,c.cv)(e,g)),f||(f=(0,c.Ur)(e,g))}else h&&(f=(0,d.YC)(i)?(0,c.dy)(e,i):(0,c.Z1)(e,i));return{replyingToId:l,editingId:u,message:g,sender:f,shouldAnimate:m,forwardedMessagesCount:h?r.length:void 0}}))((e=>{let{replyingToId:t,editingId:n,message:s,sender:o,shouldAnimate:r,forwardedMessagesCount:c,onClear:l}=e;const{setReplyingToId:d,setEditingId:u,focusMessage:m,exitForwardMode:h}=(0,a.Sv)(),g=Boolean((t||n)&&s||o&&c),f=(0,ii.Z)([c],c?300:void 0),{shouldRender:p,transitionClassNames:v}=(0,ye.Z)(f&&g,void 0,!r,void 0,!r),I=(0,i.I4)((()=>{t?d({messageId:void 0}):n?u({messageId:void 0}):c&&h(),null==l||l()}),[t,n,c,l,d,u,h]);(0,i.d4)((()=>g?(0,Ae.Z)(I):void 0),[g,I]);const y=(0,i.I4)((()=>{m({chatId:s.chatId,messageId:s.id})}),[m,s]),w=(0,fe.Z)("ComposerEmbeddedMessage",v),Z=c&&c>1?`${c} forwarded messages`:void 0;if(p)return i.ZP.createElement("div",{className:w},i.ZP.createElement("div",null,i.ZP.createElement(ze.Z,{round:!0,faded:!0,color:"translucent",ariaLabel:"Cancel replying",onClick:I},i.ZP.createElement("i",{className:"icon-close"})),i.ZP.createElement(_n,{className:"inside-input",message:s,sender:o,customText:Z,title:n?"Edit Message":void 0,onClick:y})))}))),ri=(0,i.X$)((e=>{const{attachments:t}=e,n=(0,ot.Z)(it.gl.Extra,"AttachmentModal",!t.length);return n?i.ZP.createElement(n,e):void 0})),ci=(0,i.X$)((e=>{const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"BotCommandMenu",!t);return n?i.ZP.createElement(n,e):void 0})),li=(0,i.X$)((e=>{const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"PollModal",!t);return n?i.ZP.createElement(n,e):void 0})),di=(0,i.X$)((e=>{const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"DropArea",!t);return n?i.ZP.createElement(n,e):void 0})),ui=new RegExp(s.FM,"i"),mi=(0,i.X$)((0,a.c$)(((e,t)=>{let{chatId:n,threadId:a}=t;const s=(0,c.tV)(e,n,a);return{theme:(0,c.Pu)(e),webPagePreview:e.webPagePreview,noWebPage:s}}))((e=>{let{chatId:t,threadId:n,messageText:s,disabled:r,webPagePreview:c,noWebPage:l,theme:d}=e;const{loadWebPagePreview:u,clearWebPagePreview:m,toggleMessageWebPage:h}=(0,a.Sv)(),g=xs((()=>{const{text:e,entities:t}=(0,v.Z)(s),n=t&&t.find((e=>{let{type:t}=e;return t===o.Vv.TextUrl}));if(n)return n.url;const a=e.match(ui);return a?a[0]:void 0}),300,[s]);(0,i.d4)((()=>{g?u({text:g}):(m(),h({chatId:t,threadId:n}))}),[t,h,m,g,u,n]),(0,Pe.Z)((()=>{m(),h({chatId:t,threadId:n})}),[t]);const f=Boolean(c&&s.length&&!l&&!r),{shouldRender:p,transitionClassNames:I}=(0,ye.Z)(f),y=(0,Tt.Z)(c,!0);if(!p||!y)return;const{photo:w,...Z}=y,P={content:{webPage:Z}};return i.ZP.createElement("div",{className:(0,fe.Z)("WebPagePreview",I)},i.ZP.createElement("div",null,i.ZP.createElement(ze.Z,{round:!0,faded:!0,color:"translucent",ariaLabel:"Clear Webpage Preview",onClick:()=>{h({chatId:t,threadId:n,noWebPage:!0})}},i.ZP.createElement("i",{className:"icon-close"})),i.ZP.createElement(Ea,{message:P,inPreview:!0,theme:d})))}))),hi=(0,i.X$)((e=>{const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"SendAsMenu",!t);return n?i.ZP.createElement(n,e):void 0}));var gi;!function(e){e.Send="send",e.Record="record",e.Edit="edit",e.Schedule="schedule"}(gi||(gi={}));const fi="wonderful-voice-message.ogg",pi=(0,i.X$)((0,a.c$)(((e,t)=>{var n,a,i,r;let{chatId:l,threadId:u,messageListType:m}=t;const h=(0,c.Z1)(e,l),g=l!==s.FV?(0,c.IK)(e,l):void 0,f=Boolean(g),p=(0,c.FM)(e,l),v=f&&(0,c.FT)(e,l),I=(0,c.qy)(e,l),{language:y,shouldSuggestStickers:w}=e.settings.byKey,Z=e.emojiKeywords[s.pR],P=y!==s.pR?e.emojiKeywords[y]:void 0,C=v?v.id:void 0,b=C?(0,c.hj)(e,l,C):void 0,{currentUserId:S}=e,E=null!=h&&h.fullInfo?(null==h||null===(n=h.fullInfo)||void 0===n?void 0:n.sendAsId)||S:void 0,M=null!=h&&h.sendAsIds&&E&&h.sendAsIds.includes(E)?E:null!=h&&null!==(a=h.adminRights)&&void 0!==a&&a.anonymous?null==h?void 0:h.id:void 0,k=M?(0,c.dy)(e,M):void 0,R=!k&&M?(0,c.Z1)(e,M):void 0,N="scheduled"===m?(0,c.hI)(e,l):(0,c.s)(e,l,u);return{editingMessage:(0,c.kK)(e,l,u,m),connectionState:e.connectionState,draft:(0,c.Ms)(e,l,u),chat:h,isChatWithBot:f,isChatWithSelf:p,canScheduleUntilOnline:(0,c.Eh)(e,l),isChannel:h?(0,d.eA)(h):void 0,isRightColumnShown:(0,c.Jf)(e),isSelectModeActive:(0,c.CA)(e),withScheduledButton:u===o._f&&"thread"===m&&Boolean(null==I?void 0:I.length),shouldSchedule:"scheduled"===m,botKeyboardMessageId:C,botKeyboardPlaceholder:null==b?void 0:b.keyboardPlaceholder,isForwarding:l===e.forwardMessages.toChatId,isPollModalOpen:e.isPollModalOpen,stickersForEmoji:e.stickers.forEmoji.stickers,groupChatMembers:null==h||null===(i=h.fullInfo)||void 0===i?void 0:i.members,topInlineBotIds:null===(r=e.topInlineBots)||void 0===r?void 0:r.userIds,currentUserId:S,lastSyncTime:e.lastSyncTime,contentToBeScheduled:e.messages.contentToBeScheduled,shouldSuggestStickers:w,recentEmojis:e.recentEmojis,baseEmojiKeywords:null==Z?void 0:Z.keywords,emojiKeywords:null==P?void 0:P.keywords,inlineBots:e.inlineBots.byUsername,isInlineBotLoading:e.inlineBots.isLoading,chatBotCommands:h&&h.fullInfo&&h.fullInfo.botCommands,botCommands:g&&g.fullInfo?g.fullInfo.botCommands||!1:void 0,sendAsUser:k,sendAsChat:R,sendAsId:M,editingDraft:N}}))((e=>{let{dropAreaState:t,shouldSchedule:n,canScheduleUntilOnline:r,isReady:c,onDropHide:u,editingMessage:m,chatId:g,threadId:p,messageListType:I,draft:y,chat:w,connectionState:Z,isChatWithBot:P,isChatWithSelf:C,isChannel:b,isRightColumnShown:S,isSelectModeActive:M,isForwarding:k,isPollModalOpen:R,botKeyboardMessageId:N,botKeyboardPlaceholder:T,withScheduledButton:B,stickersForEmoji:A,groupChatMembers:x,topInlineBotIds:O,currentUserId:U,lastSyncTime:F,contentToBeScheduled:D,shouldSuggestStickers:$,baseEmojiKeywords:q,emojiKeywords:j,recentEmojis:G,inlineBots:H,isInlineBotLoading:_,botCommands:z,chatBotCommands:V,sendAsUser:X,sendAsChat:K,sendAsId:W,editingDraft:Y}=e;const{sendMessage:J,clearDraft:ee,showDialog:te,setStickerSearchQuery:ne,setGifSearchQuery:ae,forwardMessages:se,openPollModal:ie,closePollModal:oe,loadScheduledHistory:re,openChat:ce,addRecentEmoji:le,sendInlineBotResult:de,loadSendAs:ue,loadFullChat:me}=(0,a.Sv)(),he=(0,Fe.Z)(),ge=(0,i.sO)(null),[pe,ve]=(0,i.eJ)(""),Ie=(0,ws.Y)(pe),ye=(0,i.sO)(),Ce=(0,Mt.Z)(t),{width:be}=Q.Z.get(),Se=null==w?void 0:w.sendAsIds,Ee=Se&&(Se.length>1||!Se.includes(U)),[Me,ke,Re]=(0,Oe.Z)(),Ne=(0,ys.Z)(g,p),Te=(0,i.I4)((()=>{Re()}),[Re]),[Be,xe]=(0,qs.Z)(r,Te);(0,i.d4)((()=>{ye.current=void 0}),[g]),(0,i.d4)((()=>{g&&F&&p===o._f&&c&&re({chatId:g})}),[c,g,re,F,p]),(0,i.d4)((()=>{g&&w&&F&&!Se&&c&&(0,d.ZV)(w)&&ue({chatId:g})}),[w,g,c,F,ue,Se]),(0,i.d4)((()=>{g&&w&&F&&!w.fullInfo&&c&&(0,d.ZV)(w)&&me({chatId:g})}),[w,g,c,F,me]);const Le=(0,i.sO)(!1);(0,Pe.Z)((e=>{let[t,n]=e;Le.current=Boolean(g===t&&Se&&!n)}),[g,Se]),(0,i.bt)((()=>{ge.current&&(ge.current.innerHTML='')}),[]);const[Ue,De]=(0,i.eJ)([]),[$e,qe,je]=(0,Oe.Z)(),[Ge,He,_e]=(0,Oe.Z)(),[Ve,Xe,Ke]=(0,Oe.Z)(),[We,Je,Qe]=(0,Oe.Z)(),[et,tt,nt]=(0,Oe.Z)(),[at,st]=(0,Oe.Z)(),[it,ot,rt]=(0,Oe.Z)(),{startRecordingVoice:ct,stopRecordingVoice:lt,pauseRecordingVoice:dt,activeVoiceRecording:ut,currentRecordTime:mt,recordButtonRef:ht,startRecordTimeRef:gt}=(()=>{const e=(0,i.sO)(null),[t,n]=(0,i.eJ)(),a=(0,i.sO)(),[s,o]=(0,i.eJ)();(0,i.d4)((()=>{h.s$&&h.mh&&Es()}),[]);const r=(0,i.I4)((async()=>{try{const{stop:t,pause:s}=await Ms((t=>{e.current&&(a.current&&Date.now()%4==0&&(e.current.style.boxShadow=`0 0 0 ${50*(t||0)}px rgba(0,0,0,.15)`),o(Date.now()))}));a.current=Date.now(),o(Date.now()),n({stop:t,pause:s})}catch(e){console.error(e)}}),[]),c=(0,i.I4)((()=>{if(t){e.current&&(e.current.style.boxShadow="none");try{return t.pause()}catch(e){return void console.error(e)}}}),[t]),l=(0,i.I4)((()=>{if(t){n(void 0),a.current=void 0,o(void 0),e.current&&(e.current.style.boxShadow="none");try{return t.stop()}catch(e){return void console.error(e)}}}),[t]);return(0,i.d4)((()=>t?(0,Ae.Z)(l):void 0),[t,l]),{startRecordingVoice:r,pauseRecordingVoice:c,stopRecordingVoice:l,activeVoiceRecording:t,currentRecordTime:s,recordButtonRef:e,startRecordTimeRef:a}})();(0,wn.Z)((()=>{Ne({type:"recordAudio"})}),ut&&s.o_),(0,i.d4)((()=>{ut||Ne({type:"cancel"})}),[ut,Ne]);const ft=m?gi.Edit:!h.mh||ut||pe&&!Ue.length||k?n?gi.Schedule:gi.Send:gi.Record,pt=!n,{isMentionTooltipOpen:vt,closeMentionTooltip:It,insertMention:yt,mentionFilteredUsers:wt}=(0,As.Z)(!Ue.length,Ie,ve,void 0,x,O,U),{isOpen:Pt,id:Ct,isGallery:bt,switchPm:St,results:Et,closeTooltip:kt,help:Rt,loadMore:Nt}=function(e,t,n,s){const{queryInlineBot:o,resetInlineBot:r}=(0,a.Sv)(),[c,l,d]=(0,Oe.Z)(),{username:u,query:m,canShowHelp:h,usernameLowered:g}=xs((()=>function(e){const t=function(e){return Fs.innerHTML=e.replace(/
/g,"\n"),Fs.innerText}(e),n=t.match(Ls);return n?{username:n[1],query:n[2],canShowHelp:""===n[2]&&!t.match(Os),usernameLowered:n[1].toLowerCase()}:Us}(n)),300,[n])||{},f=(0,Mt.Z)(m),p=(0,Mt.Z)(u),v=g?null==s?void 0:s[g]:void 0,{id:I,switchPm:y,offset:w,results:Z,isGallery:P,help:C}=v||{};(0,i.d4)((()=>{f!==m&&d()}),[f,m,d]),(0,i.d4)((()=>{e&&g&&t&&o({chatId:t,username:g,query:m})}),[m,e,o,t,g]);const b=(0,i.I4)((()=>{o({chatId:t,username:g,query:m,offset:w})}),[w,t,m,o,g]);return(0,i.d4)((()=>{e&&I&&(y||null!=Z&&Z.length)?l():d()}),[I,e,l,Z,y,d]),p!==u&&r({username:p}),{isOpen:c,id:I,isGallery:P,switchPm:y,results:Z,closeTooltip:d,help:h&&C?`@${u} ${C}`:void 0,loadMore:b}}(Boolean(!Ue.length&&F),g,pe,H),{isOpen:Tt,close:Bt,filteredBotCommands:At}=function(e,t,n,a){const[s,o,r]=(0,Oe.Z)(),[c,l]=(0,i.eJ)(),d=(0,i.I4)((e=>{n||a?Ds((()=>{const t=(n||a||[]).filter((t=>{let{command:n}=t;return!e||n.includes(e)}));l(t&&t.length?t:void 0)})):l(void 0)}),[n,a]);return(0,i.d4)((()=>{if(e&&t.length)if(t.startsWith("/")){const e=(0,Is._)(t.substr(1)).match($s);d(e?e[0]:"")}else l(void 0);else l(void 0)}),[d,t,e,r]),(0,i.d4)((()=>{c&&c.length?o():r()}),[c,o,r]),{isOpen:s,close:r,filteredBotCommands:c}}(Boolean(z&&z.length||V&&V.length),pe,z,V),{isContextMenuOpen:xt,handleContextMenu:Lt,handleContextMenuClose:Ot,handleContextMenuHide:Ut}=(0,Sn.Z)(ht,!(ft===gi.Send&&pt)),{canSendStickers:Ft,canSendGifs:Dt,canAttachMedia:$t,canAttachPolls:qt,canAttachEmbedLinks:jt}=(0,i.Ye)((()=>(0,d.H5)(w,P)),[w,P]),Gt=w&&(0,d.Nl)(w),Ht=(0,d.Hd)(w),{isStickerTooltipOpen:_t,closeStickerTooltip:zt}=function(e,t,n){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const o=(0,i.Ye)((()=>(0,Is._)(t).trim()),[t]),{loadStickersForEmoji:r,clearStickersForEmoji:c}=(0,a.Sv)(),l=h.op&&1===(0,vs.Z)(o)||!h.op&&Boolean(t.match(/^]*?>$/g)),d=Boolean(n)&&l;return(0,i.d4)((()=>{var t;s||(e&&l?r({emoji:h.op?o:null===(t=o.match(/alt="(.+)"/))||void 0===t?void 0:t[1]}):!d&&l||c())}),[t,l,c,r,e,s]),{isStickerTooltipOpen:d,closeStickerTooltip:c}}(Boolean($&&Ft&&!Ue.length),pe,A,!c),{isEmojiTooltipOpen:Vt,closeEmojiTooltip:Xt,filteredEmojis:Kt,insertEmoji:Wt}=(0,Bs.Z)(Boolean($&&Ft&&!Ue.length),Ie,G,void 0,ve,q,j,!c),Yt=(0,i.I4)((function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s.R2;const n=window.getSelection(),a=document.getElementById(t),i=(0,nn.Z)(e,["escape_html","emoji_html","br_html"]).join("").replace(/\u200b+/g,"​");if(n.rangeCount){const e=n.getRangeAt(0);if((0,gs.R)(e,t))return hs(i),void a.dispatchEvent(new Event("input",{bubbles:!0}))}ve(`${Ie.current}${i}`),requestAnimationFrame((()=>{(0,ls.Z)(a)}))}),[Ie]),Jt=(0,i.I4)((()=>{const e=window.getSelection();if(e.rangeCount){const t=e.getRangeAt(0);if((0,gs.R)(t,s.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 n=t.lastChild;if(n.lastChild)for(;n.lastChild;)n=n.lastChild;const a=n.textContent.length,s=document.createRange(),i=window.getSelection();s.setStart(n,a),s.setEnd(n,a),i.removeAllRanges(),i.addRange(s),document.execCommand("delete",!1);const o=t.innerHTML;return document.body.removeChild(t),o}(Ie.current))}),[Ie]),Qt=(0,i.I4)((function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];e||ve(""),De(l.D),zt(),It(),Xt(),h.wB?setTimeout((()=>Ke()),350):Ke()}),[zt,It,Xt,Ke]),en=(0,i.sO)();en.current=lt,(0,i.d4)((()=>()=>{en.current(),Qt()}),[g,Qt,en]);const[tn,an]=((e,t,n,o,r,c,l,u,m,h)=>{const{editMessage:g,setEditingDraft:f}=(0,a.Sv)();(0,hn.Z)((e=>{let[a]=e;if(!n)return;if((null==a?void 0:a.id)===n.id)return;const i=(0,va.z)(null!=h&&h.text.length?h:n.content.text);t(i),requestAnimationFrame((()=>{const e=document.getElementById(s.R2);(0,ls.Z)(e,!0)}))}),[n,t]),(0,i.d4)((()=>{if(n)return()=>{const t=(0,v.Z)(e.current),n=t.text.length?t:void 0;f({chatId:c,threadId:l,type:u,text:n})}}),[c,n,e,f,l,u]);const p=(0,i.I4)((()=>{m&&(0,E.T2)((()=>{t((0,va.z)(m));const e=document.getElementById(s.R2);requestAnimationFrame((()=>{(0,ls.Z)(e,!0)}))}))}),[m,t]),I=(0,i.I4)((()=>{o(),p()}),[o,p]),y=(0,i.I4)((()=>{const{text:t,entities:a}=(0,v.Z)(e.current);n&&(t||(0,d.u8)(n)?(g({messageId:n.id,text:t,entities:a}),o(),p()):r())}),[g,n,e,r,o,p]),w=(0,i.I4)((()=>{if(!n)return;const t=(0,v.Z)(e.current),a=t.text.length?t:void 0;f({chatId:c,threadId:l,type:u,text:a})}),[c,n,e,f,l,u]);return(0,we.Z)(w),Ze(w),[y,I]})(Ie,ve,m,Qt,tt,g,p,I,y,Y);((e,t,n,o,r,c)=>{const{saveDraft:l,clearDraft:d}=(0,a.Sv)(),u=(0,i.I4)(((e,t)=>{const n=o.current;c||(n.length?l({chatId:e,threadId:t,draft:(0,v.Z)(n)}):void 0!==n&&d({chatId:e,threadId:t}))}),[d,c,o,l]),m=(0,i.Ye)((()=>(0,E.Ds)((e=>e()),s.r_,!1)),[t]),g=(0,Mt.Z)(t),f=(0,Mt.Z)(n);(0,i.d4)((()=>(Ns=t,Ts=n,()=>{Ns=void 0,Ts=void 0,u(t,n)})),[t,n,u]),(0,i.d4)((()=>{t===g&&n===f||!c&&e&&(r((0,va.z)(e)),h.$b||requestAnimationFrame((()=>{const e=document.getElementById(s.R2);(0,ls.Z)(e,!0)})))}),[t,n,e,r,u,g,f,c]);const p=o.current,I=(0,Mt.Z)(p);(0,i.d4)((()=>{t&&n&&g===t&&f===n&&I!==p&&(p.length?m((()=>{Ns===t&&Ts===n&&u(t,n)})):u(t,n))}),[t,p,g,I,f,m,n,u]);const y=(0,i.I4)((()=>{t&&n&&u(t,n)}),[t,n,u]);(0,we.Z)(y),Ze(y)})(y,g,p,Ie,ve,m),((e,t,n)=>{(0,i.d4)((()=>{async function a(a){if(!a.clipboardData)return;const i=document.activeElement;if(i&&![s.R2,s.nY].includes(i.id))return;const o=a.clipboardData.getData("text").substring(0,4096),{items:r}=a.clipboardData;let c=[];if(a.preventDefault(),r.length>0&&(c=await(0,ks.Z)(r)),0!==c.length||o){if(c.length>0&&!n){const e=await Promise.all(c.map((e=>ms(e.name,e,1===c.length&&Rs.includes(e.type)))));t((t=>t.concat(e)))}o&&e(o,null==i?void 0:i.id)}}return document.addEventListener("paste",a,!1),()=>{document.removeEventListener("paste",a,!1)}}),[e,n,t])})(Yt,De,m);const sn=(0,i.I4)((()=>{m&&an()}),[m,an]),on=(0,i.I4)((async(e,t)=>{De(await Promise.all(e.map((e=>ms(e.name,e,t)))))}),[]),cn=(0,i.I4)((async(e,t)=>{De([...Ue,...await Promise.all(e.map((e=>ms(e.name,e,t))))])}),[Ue]),ln=(0,i.I4)((()=>{De(l.D)}),[]),dn=(0,i.I4)((async function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;if("connectionStateReady"!==Z)return;let n=Ue;if(ut){const e=await lt();if(e){const{blob:t,duration:a,waveform:s}=e;n=[await ms(fi,t,!1,{voice:{duration:a,waveform:s}})]}}const{text:i,entities:o}=(0,v.Z)(Ie.current);if(!n.length&&!i&&!k)return;const{serverTimeOffset:r}=(0,a.Rd)(),c=n.length?1024:4096;if((null==i?void 0:i.length)>c){const e=i.length-c;return void te({data:{message:"MESSAGE_TOO_LONG_PLEASE_REMOVE_CHARACTERS",textParams:{"{EXTRA_CHARS_COUNT}":e,"{PLURAL_S}":e>1?"s":""},hasErrorKey:!0}})}const l=document.getElementById(s.R2);if(n.length||i){if(Ht&&!Gt){const e=(0,f.b)(r),t=ye.current&&Math.floor(e-ye.current),n=Ht.nextSendDate&&Ht.nextSendDate>e;if(t&&t{Qt()}))}),[Z,Ue,ut,k,ee,g,Qt,lt,te,Ht,Gt,J,se,he,Ie]),un=(0,i.I4)((()=>{Ke(),He()}),[Ke,He]),mn=(0,i.I4)((()=>{_e(),Qe(),Xe()}),[_e,Qe,Xe]),gn=(0,i.I4)(((e,t)=>{if(e&&"queryId"in e){const{id:n,queryId:a,isSilent:s}=e;return void de({id:n,queryId:a,scheduledAt:t,isSilent:s})}const{isSilent:n,...a}=e||{};e&&0!==Object.keys(a).length?J({...e,scheduledAt:t}):dn(Boolean(n),t)}),[dn,de,J]);(0,i.d4)((()=>{D&&Be((e=>{gn(D,e)}))}),[D,gn,Be]);const fn=(0,i.I4)((function(e,t,a){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];e={...e,isPreloadedGlobally:!0},n||a?(ke(),Be((n=>{Re(),gn({sticker:e,isSilent:t},n),requestAnimationFrame((()=>{Qt(s)}))}))):(J({sticker:e,isSilent:t}),requestAnimationFrame((()=>{Qt(s)})))}),[n,ke,Be,Re,gn,Qt,J]),pn=(0,i.I4)(((e,t,a)=>{n||a?(ke(),Be((n=>{Re(),gn({gif:e,isSilent:t},n),requestAnimationFrame((()=>{Qt(!0)}))}))):(J({gif:e,isSilent:t}),requestAnimationFrame((()=>{Qt(!0)})))}),[n,ke,Be,Re,gn,Qt,J]),vn=(0,i.I4)(((e,t,a)=>{if("connectionStateReady"!==Z)return;n||a?Be((n=>{gn({id:e.id,queryId:e.queryId,isSilent:t},n)})):de({id:e.id,queryId:e.queryId,isSilent:t});const i=document.getElementById(s.R2);h.cj&&i===document.activeElement&&ps(i),ee({chatId:g,localOnly:!0}),requestAnimationFrame((()=>{Qt()}))}),[g,ee,Z,gn,Be,Qt,de,n]),In=(0,i.I4)((()=>{ee({chatId:g,localOnly:!0}),requestAnimationFrame((()=>{Qt()}))}),[g,ee,Qt]),yn=(0,i.I4)((e=>{n?(Be((t=>{gn({poll:e},t)})),oe()):(J({poll:e}),oe())}),[oe,gn,Be,J,n]),Zn=(0,i.I4)((()=>{n?Be((e=>{gn({isSilent:!0},e)})):dn(!0)}),[gn,dn,Be,n]),Pn=(0,i.I4)((e=>{"stickers"===e?(ne({query:""}),ae({query:void 0})):(ae({query:""}),ne({query:void 0}))}),[ne,ae]),Cn=(0,i.I4)((()=>{const e=document.getElementById(s.R2);h.wB&&e===document.activeElement?(e.blur(),setTimeout((()=>{_e(),Xe()}),100)):Xe()}),[Xe,_e]),bn=(0,i.I4)((()=>{const e=document.getElementById(s.R2);if(!h.wB||e!==document.activeElement)return _e(),Ke(),void Je();e.blur(),setTimeout((()=>{_e(),Ke(),Je()}),100)}),[_e,Ke,Je]),En=(0,i.I4)((()=>{ce({id:g,threadId:p,type:"scheduled"})}),[ce,g,p]);(0,i.d4)((()=>{S&&h.wB&&Ke()}),[S,Ke]),(0,i.d4)((()=>{c&&(M?ot():setTimeout((()=>{rt()}),200))}),[M,rt,ot,c]);const Mn=(0,i.I4)((()=>{switch(ft){case gi.Send:dn();break;case gi.Record:ct();break;case gi.Edit:tn();break;case gi.Schedule:ut&&dt(),Be((e=>{gn({},e)}))}}),[ft,dn,ct,tn,ut,Be,dt,gn]),kn=ft===gi.Record&&!$t,Rn=(0,Mt.Z)(m,!0),Nn=m||Rn,Tn=new Date;Tn.setSeconds(0),Tn.setMilliseconds(0);const Bn=new Date;Bn.setFullYear(Bn.getFullYear()+1);let An="SendMessage";switch(ft){case gi.Edit:An="Save edited message";break;case gi.Record:An=kn?"Conversation.DefaultRestrictedMedia":"AccDescrVoiceMessage"}const xn=(0,fe.Z)("Composer",!M&&"shown",it&&"hover-disabled"),Ln=(0,fe.Z)("mobile-symbol-menu-button",!c&&"not-ready",at?Ve&&"menu-opened":Ve&&"is-loading"),On=(0,i.I4)((()=>{Be((e=>{gn({},e)}))}),[gn,Be]),Un=ft===gi.Edit?tn:ft===gi.Schedule?On:dn;return i.ZP.createElement("div",{className:xn},$t&&c&&i.ZP.createElement(di,{isOpen:t!==Zt.t.None,withQuick:t===Zt.t.QuickFile||Ce===Zt.t.QuickFile,onHide:u,onFileSelect:on}),i.ZP.createElement(ri,{chatId:g,threadId:p,canShowCustomSendMenu:pt,attachments:Ue,caption:Ue.length?pe:"",groupChatMembers:x,currentUserId:U,recentEmojis:G,isReady:c,isChatWithSelf:C,onCaptionUpdate:ve,baseEmojiKeywords:q,emojiKeywords:j,addRecentEmoji:le,shouldSchedule:n,onSendSilent:Zn,onSend:dn,onSendScheduled:On,onFileAppend:cn,onClear:ln}),i.ZP.createElement(li,{isOpen:Boolean(R),shouldBeAnonimous:b,onClear:oe,onSend:yn}),Nn&&i.ZP.createElement(js,{isOpen:et,isSchedule:"scheduled"===I,onClose:nt,message:Nn}),i.ZP.createElement(hi,{isOpen:We,onClose:Qe,chatId:g,selectedSendAsId:W,sendAsIds:Se}),i.ZP.createElement(Js,{isOpen:vt,onClose:It,onInsertUserName:yt,filteredUsers:wt}),i.ZP.createElement(Ys,{isOpen:Pt,botId:Ct,isGallery:bt,inlineBotResults:Et,switchPm:St,onSelectResult:vn,loadMore:Nt,onClose:kt,isSavedMessages:C,canSendGifs:Dt}),i.ZP.createElement(ni,{isOpen:Tt,withUsername:Boolean(V),botCommands:At,onClick:In,onClose:Bt}),i.ZP.createElement("div",{id:"message-compose"},i.ZP.createElement("div",{className:"svg-appendix",ref:ge}),i.ZP.createElement(oi,{onClear:sn}),i.ZP.createElement(mi,{chatId:g,threadId:p,messageText:Ue.length?"":pe,disabled:!jt}),i.ZP.createElement("div",{className:"message-input-wrapper"},P&&!1!==z&&!ut&&!m&&i.ZP.createElement(zs,{className:(0,fe.Z)("bot-commands",Ge&&"activated"),round:!0,disabled:void 0===z,color:"translucent",onActivate:un,ariaLabel:"Open bot command keyboard"},i.ZP.createElement("i",{className:"icon-bot-commands-filled"})),Ee&&(X||K)&&i.ZP.createElement(ze.Z,{round:!0,color:"translucent",onClick:We?Qe:bn,ariaLabel:he("SendMessageAsTitle"),className:(0,fe.Z)("send-as-button",Le.current&&"appear-animation")},i.ZP.createElement(rn.Z,{user:X,chat:K,size:"tiny"})),h.wB?i.ZP.createElement(ze.Z,{className:Ln,round:!0,color:"translucent",onClick:Ve?Ke:Cn,ariaLabel:"Choose emoji, sticker or GIF"},i.ZP.createElement("i",{className:"icon-smile"}),i.ZP.createElement("i",{className:"icon-keyboard"}),Ve&&!at&&i.ZP.createElement(Ye.Z,{color:"gray"})):i.ZP.createElement(zs,{className:Ve?"activated":"",round:!0,color:"translucent",onActivate:mn,ariaLabel:"Choose emoji, sticker or GIF"},i.ZP.createElement("i",{className:"icon-smile"})),i.ZP.createElement(si.Z,{id:"message-input-text",chatId:g,threadId:p,html:Ue.length?"":pe,placeholder:ut&&be<=600?"":T||he("Message"),forcedPlaceholder:Rt,canAutoFocus:c&&!Ue.length,shouldSuppressFocus:h.wB&&Ve,shouldSuppressTextFormatter:Vt||vt||Pt,onUpdate:ve,onSend:Un,onSuppressedFocus:Ke}),_&&Boolean(Ct)&&i.ZP.createElement(Ye.Z,{color:"gray"}),B&&i.ZP.createElement(ze.Z,{round:!0,faded:!0,className:"scheduled-button",color:"translucent",onClick:En,ariaLabel:"Open scheduled messages"},i.ZP.createElement("i",{className:"icon-schedule"})),N&&!ut&&!m&&i.ZP.createElement(zs,{className:$e?"activated":"",round:!0,color:"translucent",onActivate:qe,ariaLabel:"Open bot command keyboard"},i.ZP.createElement("i",{className:"icon-bot-command"})),ut&&mt&&i.ZP.createElement("span",{className:"recording-state"},(0,L.rM)(mt-gt.current)),i.ZP.createElement(ei,{chatId:g,threadId:p,isOpen:_t,onStickerSelect:fn}),i.ZP.createElement(ti.Z,{isOpen:Vt,emojis:Kt,onClose:Xt,onEmojiSelect:Wt,addRecentEmoji:le}),i.ZP.createElement(Ks,{isButtonVisible:!ut&&!m,canAttachMedia:$t,canAttachPolls:qt,onFileSelect:on,onPollCreate:ie}),N&&i.ZP.createElement(ai,{messageId:N,isOpen:$e,onClose:je}),z&&i.ZP.createElement(ci,{isOpen:Ge,botCommands:z,onClose:_e}),i.ZP.createElement(Ws,{chatId:g,threadId:p,isOpen:Ve||Me,canSendGifs:Dt,canSendStickers:Ft,onLoad:st,onClose:Ke,onEmojiSelect:Yt,onStickerSelect:fn,onGifSelect:pn,onRemoveSymbol:Jt,onSearchOpen:Pn,addRecentEmoji:le}))),ut&&i.ZP.createElement(ze.Z,{round:!0,color:"danger",className:"cancel",onClick:lt,ariaLabel:"Cancel voice recording"},i.ZP.createElement("i",{className:"icon-delete"})),i.ZP.createElement(ze.Z,{ref:ht,round:!0,color:"secondary",className:(0,fe.Z)(ft,!c&&"not-ready",ut&&"recording"),disabled:kn,ariaLabel:he(An),onClick:Mn,onContextMenu:ft===gi.Send&&pt?Lt:void 0},i.ZP.createElement("i",{className:"icon-send"}),i.ZP.createElement("i",{className:"icon-schedule"}),i.ZP.createElement("i",{className:"icon-microphone-alt"}),i.ZP.createElement("i",{className:"icon-check"})),pt&&i.ZP.createElement(Qs.Z,{isOpen:xt,onSendSilent:C?void 0:Zn,onSendSchedule:n?void 0:On,onClose:Ot,onCloseAnimationEnd:Ut,isSavedMessages:C}),xe)}))),vi=(0,i.X$)((e=>{const{isActive:t}=e,n=(0,ot.Z)(it.gl.Extra,"MobileSearch",!t,!0);return n?i.ZP.createElement(n,e):void 0})),Ii=(0,i.X$)((e=>{const{isActive:t}=e,n=(0,ot.Z)(it.gl.Extra,"MessageSelectToolbar",!t);return n?i.ZP.createElement(n,e):void 0})),yi=(0,i.X$)((e=>{const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"UnpinAllMessagesModal",!t);return n?i.ZP.createElement(n,e):void 0})),wi=(0,i.X$)((e=>{const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"PaymentModal",!t);return n?i.ZP.createElement(n,e):void 0})),Zi=(0,i.X$)((e=>{const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"ReceiptModal",!t);return n?i.ZP.createElement(n,e):void 0})),Pi=(0,i.X$)((e=>{const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"SeenByModal",!t);return n?i.ZP.createElement(n,e):void 0})),Ci=(0,i.X$)((e=>{const{activeEmojiInteraction:t}=e,n=(0,ot.Z)(it.gl.Extra,"EmojiInteractionAnimation",!t);return n?i.ZP.createElement(n,e):void 0})),bi=(0,i.X$)((e=>{const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"ReactorListModal",!t);return n?i.ZP.createElement(n,e):void 0})),Si=h.wB?450+s.fK:void 0;function Ei(e){return"file"===e.kind&&e.type&&s.oG.has(e.type)}const Mi=(0,i.X$)((0,a.c$)((e=>{const t=(0,c.Pu)(e),{isBlurred:n,background:a,backgroundColor:s,patternColor:i}=e.settings.themes[t]||{},{messageLists:r}=e.messages,l=(0,c.Bt)(e),{isLeftColumnShown:u,chats:{listIds:m},activeEmojiInteractions:g,lastSyncTime:f}=e,p={theme:t,customBackground:a,backgroundColor:s,patternColor:i,isLeftColumnShown:u,isRightColumnShown:(0,c.Jf)(e),isBackgroundBlurred:n,isMobileSearchActive:Boolean(h.wB&&(0,c.n5)(e)),isSelectModeActive:(0,c.CA)(e),isPaymentModalOpen:e.payment.isPaymentModalOpen,isReceiptModalOpen:Boolean(e.payment.receipt),isSeenByModalOpen:Boolean(e.seenByModal),isReactorListModalOpen:Boolean(e.reactorModal),animationLevel:e.settings.byKey.animationLevel,currentTransitionKey:Math.max(0,e.messages.messageLists.length-1),activeEmojiInteractions:g,lastSyncTime:f};if(!l||!m.active)return p;const{chatId:v,threadId:I,type:y}=l,w=(0,d.YC)(v),Z=(0,c.Z1)(e,v),P=(0,c.IK)(e,v),C=(0,c.KB)(e,v),{chatId:b,messageId:S}=e.audioPlayer,E=Z&&(0,d.Qm)(Z,I),M=(0,c.pk)(e,v),k="pinned"===y,R="scheduled"===y,N="thread"===y&&I===o._f,T=Boolean(Z&&(0,d.eA)(Z)),B=Boolean(Z&&N&&(T||(0,d.ZV)(Z))&&Z.isNotJoined),A=Boolean(P&&(0,c.s4)(e,P.id)),x=!A&&M;return{...p,chatId:v,threadId:I,messageListType:y,isPrivate:w,areChatSettingsLoaded:Boolean(null==Z?void 0:Z.settings),canPost:!k&&(!Z||E)&&!M,isPinnedMessageList:k,isScheduledMessageList:R,currentUserBannedRights:null==Z?void 0:Z.currentUserBannedRights,defaultBannedRights:null==Z?void 0:Z.defaultBannedRights,hasPinnedOrAudioPlayer:I!==o._f||Boolean(!k&&(null==C?void 0:C.length))||Boolean(b&&S),pinnedMessagesCount:C?C.length:0,shouldSkipHistoryAnimations:e.shouldSkipHistoryAnimations,messageLists:r,isChannel:T,canSubscribe:B,canStartBot:x,canRestartBot:A}}))((e=>{let{chatId:t,threadId:n,messageListType:o,isPrivate:r,isPinnedMessageList:c,messageLists:l,canPost:u,currentUserBannedRights:m,defaultBannedRights:g,hasPinnedOrAudioPlayer:f,pinnedMessagesCount:p,customBackground:v,theme:I,backgroundColor:y,patternColor:w,isLeftColumnShown:Z,isRightColumnShown:P,isBackgroundBlurred:C,isMobileSearchActive:b,isSelectModeActive:S,isPaymentModalOpen:E,isReceiptModalOpen:M,isSeenByModalOpen:k,isReactorListModalOpen:R,animationLevel:N,shouldSkipHistoryAnimations:T,currentTransitionKey:B,isChannel:A,areChatSettingsLoaded:x,canSubscribe:L,canStartBot:O,canRestartBot:U,activeEmojiInteractions:F,lastSyncTime:D}=e;const{openChat:$,unpinAllMessages:q,loadUser:j,loadChatSettings:G,closeLocalTextSearch:H,exitMessageSelectMode:_,closePaymentModal:z,clearReceipt:V,joinChannel:X,sendBotCommand:K,restartBot:Q}=(0,a.Sv)(),{width:ee}=St(),te=(0,Fe.Z)(),[ne,ae]=(0,i.eJ)(Zt.t.None),[se,ie]=(0,i.eJ)(),[oe,re]=(0,i.eJ)(),[ce,le]=(0,i.eJ)(!1),de=f&&(ees._m&&ee=s.ks&&ee{e||o(!0)}),[e]),{isReady:s&&!c,handleOpenEnd:e?function(e){"transform"===e.propertyName&&e.target===e.currentTarget&&o(Boolean(a))}:void 0,handleSlideStop:e?function(){o(!0)}:void 0}}(!T&&N!==s.oB,B,Ce,t);(0,i.d4)((()=>t?(0,Ae.Z)((()=>{$({id:void 0})})):void 0),[t,$]),(0,Pe.Z)((()=>{ae(Zt.t.None),ie(void 0),re(void 0)}),[t]),(0,i.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,i.d4)((()=>{r&&j({userId:t})}),[t,r,j]),(0,i.d4)((()=>{!x&&D&&G({chatId:t})}),[t,r,x,D,G]);const Re=(0,i.I4)((e=>{if(h.$b)return;const{items:t}=e.dataTransfer||{},n=t&&t.length>0&&Array.from(t).filter((e=>"text/uri-list"!==e.type)).every(Ei);ae(n?Zt.t.QuickFile:Zt.t.Document)}),[]),Ne=(0,i.I4)((()=>{ae(Zt.t.None)}),[]),Te=(0,i.I4)((()=>{le(!0)}),[]),Be=(0,i.I4)((()=>{le(!1)}),[]),xe=(0,i.I4)((()=>{q({chatId:t}),Be(),$({id:t})}),[q,$,Be,t]),Le=(0,i.I4)((()=>{$({id:t})}),[$,t]),Oe=(0,i.I4)((()=>{X({chatId:t})}),[X,t]),De=(0,i.I4)((()=>{K({command:"/start"})}),[K]),$e=(0,i.I4)((()=>{Q({chatId:t})}),[t,Q]),qe=((e,t)=>{const[n,a]=(0,i.eJ)(t);return(0,i.d4)((()=>{t&&(t.startsWith("#")?a(t):Ct.fetch(s.fo,e,Ct.Type.Blob).then((e=>{const t=URL.createObjectURL(e);(0,bt.pt)(t).then((()=>{a(`url(${t})`)}))})))}),[t,e]),t?n:void 0})(I,v),je=(0,fe.Z)(ye&&"has-header-tools",v&&"custom-bg-image",y&&"custom-bg-color",v&&C&&"blurred",h.aZ?"mask-image-disabled":"mask-image-enabled"),Ge=(0,fe.Z)("messaging-disabled",!S&&"shown"),He=(0,d.q8)(te,m,g),{composerHiddenScale:_e,toolbarHiddenScale:Ve,composerTranslateX:Xe,toolbarTranslateX:Ke,unpinHiddenScale:We,toolbarForUnpinHiddenScale:Ye}=(0,i.Ye)((()=>function(e,t){const n=e<=s.l3?16:32,a=function(e){if(e>s._m){const t=Math.min(Math.max(.25*e,J),Y),n=Math.min(.25*e,Y);return Math.min(e-t-n,W)}if(e>s.ks){const t=Math.min(Math.max(.4*e,J),Y);return Math.min(e-t,W)}return e>W?W:e}(e),i=e<=s.l3?54:64,o=t?a-n-i:a-n,r=e>s.l3?Math.min(a-n,512):a-n,c=r/o,l=o/r;return{composerHiddenScale:c,toolbarHiddenScale:l,composerTranslateX:t?i/2*l:0,toolbarTranslateX:t?i/2*-1*c:0,unpinHiddenScale:r/258,toolbarForUnpinHiddenScale:258/r}}(ee,Ie)),[Ie,ee]),Je=(0,fe.Z)("middle-column-footer",!Ie&&"no-composer",Ie&&oe&&!S&&"with-notch");(0,Me.ZP)(ue&&me,(()=>{$({id:void 0},{forceSyncOnIOs:!0})}),void 0,void 0,void 0,(null==l?void 0:l.map(Pt.q))||[]),(0,Me.ZP)(b,H),(0,Me.ZP)(S,_);const Qe=Boolean(!c&&!Ie&&!ve&&!pe&&!ge&&He),et=Boolean(ve||ge||pe||c),tt=Boolean(Qe||S||c);return i.ZP.createElement("div",{id:"MiddleColumn",className:je,onTransitionEnd:Ee,style:`\n --composer-hidden-scale: ${_e};\n --toolbar-hidden-scale: ${Ve};\n --unpin-hidden-scale: ${We};\n --toolbar-unpin-hidden-scale: ${Ye};\n --composer-translate-x: ${Xe}px;\n --toolbar-translate-x: ${Ke}px;\n --pattern-color: ${w};\n --theme-background-color:\n ${y||("dark"===I?s.It:s.p3)};\n `,onClick:h.p7&&Z?Le:void 0},i.ZP.createElement("div",{id:"middle-column-bg",style:qe?`--custom-background: ${qe}`:void 0}),i.ZP.createElement("div",{id:"middle-column-portals"}),ue&&me&&i.ZP.createElement(i.ZP.Fragment,null,i.ZP.createElement("div",{className:"messages-layout",onDragEnter:Ie?Re:void 0},i.ZP.createElement(un,{chatId:ue,threadId:me,messageListType:he,isReady:Se}),i.ZP.createElement(Ue.Z,{name:T?"none":N===s.zy?"slide":"fade",activeKey:B,shouldCleanup:!0,cleanupExceptionKey:be,onStop:ke},i.ZP.createElement(rs,{key:`${ue}-${me}-${he}`,chatId:ue,threadId:me,type:he,canPost:Ie,hasTools:ye,onFabToggle:ie,onNotchToggle:re,isReady:Se,withBottomShift:et}),i.ZP.createElement("div",{className:Je},Ie&&i.ZP.createElement(pi,{chatId:ue,threadId:me,messageListType:he,dropAreaState:ne,onDropHide:Ne,isReady:Se}),c&&i.ZP.createElement("div",{className:"middle-column-footer-button-container",dir:te.isRtl?"rtl":void 0},i.ZP.createElement(ze.Z,{size:"tiny",fluid:!0,color:"secondary",className:"unpin-all-button",onClick:Te},i.ZP.createElement("i",{className:"icon-unpin"}),i.ZP.createElement("span",null,te("Chat.Pinned.UnpinAll",p,"i")))),Qe&&i.ZP.createElement("div",{className:Ge},i.ZP.createElement("div",{className:"messaging-disabled-inner"},i.ZP.createElement("span",null,He))),h.wB&&ge&&i.ZP.createElement("div",{className:"middle-column-footer-button-container",dir:te.isRtl?"rtl":void 0},i.ZP.createElement(ze.Z,{size:"tiny",fluid:!0,ripple:!0,className:"join-subscribe-button",onClick:Oe},te(Ze?"ProfileJoinChannel":"ProfileJoinGroup"))),h.wB&&pe&&i.ZP.createElement("div",{className:"middle-column-footer-button-container",dir:te.isRtl?"rtl":void 0},i.ZP.createElement(ze.Z,{size:"tiny",fluid:!0,ripple:!0,className:"join-subscribe-button",onClick:De},te("BotStart"))),h.wB&&ve&&i.ZP.createElement("div",{className:"middle-column-footer-button-container",dir:te.isRtl?"rtl":void 0},i.ZP.createElement(ze.Z,{size:"tiny",fluid:!0,ripple:!0,className:"join-subscribe-button",onClick:$e},te("BotRestart"))),i.ZP.createElement(Ii,{messageListType:he,isActive:S,canPost:Ie}),i.ZP.createElement(wi,{isOpen:Boolean(E),onClose:z}),i.ZP.createElement(Zi,{isOpen:Boolean(M),onClose:V}),i.ZP.createElement(Pi,{isOpen:k}),i.ZP.createElement(bi,{isOpen:R}))),i.ZP.createElement(cs,{isShown:we,canPost:Ie,withExtraShift:tt})),h.wB&&i.ZP.createElement(vi,{isActive:Boolean(b)})),t&&i.ZP.createElement(yi,{isOpen:ce,chatId:t,pinnedMessagesCount:p,onClose:Be,onUnpin:xe}),i.ZP.createElement("div",{teactFastList:!0},null==F?void 0:F.map(((e,t)=>i.ZP.createElement(Ci,{teactOrderKey:t,key:e.id,activeEmojiInteraction:e})))))}))),ki=(0,E.Ds)((e=>e()),200,!1);var Ri;!function(e){e[e.Profile=0]="Profile",e[e.MemberList=1]="MemberList",e[e.SharedMedia=2]="SharedMedia",e[e.Search=3]="Search",e[e.Statistics=4]="Statistics",e[e.Management=5]="Management",e[e.ManageInitial=6]="ManageInitial",e[e.ManageChannelSubscribers=7]="ManageChannelSubscribers",e[e.ManageChatAdministrators=8]="ManageChatAdministrators",e[e.ManageChatPrivacyType=9]="ManageChatPrivacyType",e[e.ManageDiscussion=10]="ManageDiscussion",e[e.ManageGroupPermissions=11]="ManageGroupPermissions",e[e.ManageGroupRemovedUsers=12]="ManageGroupRemovedUsers",e[e.ManageChannelRemovedUsers=13]="ManageChannelRemovedUsers",e[e.ManageGroupUserPermissionsCreate=14]="ManageGroupUserPermissionsCreate",e[e.ManageGroupUserPermissions=15]="ManageGroupUserPermissions",e[e.ManageGroupRecentActions=16]="ManageGroupRecentActions",e[e.ManageGroupAdminRights=17]="ManageGroupAdminRights",e[e.ManageGroupNewAdminRights=18]="ManageGroupNewAdminRights",e[e.ManageGroupMembers=19]="ManageGroupMembers",e[e.ManageGroupAddAdmins=20]="ManageGroupAddAdmins",e[e.StickerSearch=21]="StickerSearch",e[e.GifSearch=22]="GifSearch",e[e.PollResults=23]="PollResults",e[e.AddingMembers=24]="AddingMembers",e[e.ManageInvites=25]="ManageInvites",e[e.ManageEditInvite=26]="ManageEditInvite",e[e.ManageReactions=27]="ManageReactions",e[e.ManageInviteInfo=28]="ManageInviteInfo",e[e.ManageJoinRequests=29]="ManageJoinRequests"}(Ri||(Ri={}));const Ni=(0,i.X$)((0,a.c$)(((e,t)=>{var n,a,s,i;let{chatId:o,isProfile:r,isManagement:l}=t;const{query:u}=(0,c.n5)(e)||{},{query:m}=(0,c.y5)(e)||{},{query:h}=(0,c.yN)(e)||{},g=o?(0,c.Z1)(e,o):void 0,f=g&&(0,d.eA)(g),p=r&&o&&(0,d.YC)(o)?(0,c.dy)(e,o):void 0,v=p&&(0,d.kw)(p),I=Boolean(!l&&r&&!v&&g&&!(0,c.FM)(e,g.id)&&((0,d.YC)(g.id)||((0,d.Nl)(g)||g.isCreator)&&!g.isNotJoined)),y=Boolean(o&&(null===(n=e.management.byChatId[o])||void 0===n?void 0:n.editingInvite)),w=null==g||null===(a=g.fullInfo)||void 0===a?void 0:a.canViewStatistics,Z=o?null===(s=e.management.byChatId[o])||void 0===s||null===(i=s.inviteInfo)||void 0===i?void 0:i.invite:void 0;return{canManage:I,canAddContact:v,canViewStatistics:w,isChannel:f,userId:null==p?void 0:p.id,messageSearchQuery:u,stickerSearchQuery:m,gifSearchQuery:h,isEditingInvite:y,currentInviteInfo:Z}}))((e=>{var t;let{chatId:n,isColumnOpen:s,isProfile:o,isSearch:r,isManagement:c,isStatistics:l,isStickerSearch:d,isGifSearch:u,isPollResults:g,isAddingChatMembers:f,profileState:p,managementScreen:v,canAddContact:I,userId:y,canManage:w,isChannel:Z,onClose:P,onScreenSelect:C,messageSearchQuery:b,stickerSearchQuery:S,gifSearchQuery:E,shouldSkipAnimation:M,isEditingInvite:k,canViewStatistics:R,currentInviteInfo:N}=e;const{setLocalTextSearchQuery:T,setStickerSearchQuery:B,setGifSearchQuery:A,searchTextMessagesLocal:x,toggleManagement:O,openHistoryCalendar:U,openAddContactDialog:F,toggleStatistics:D,setEditingExportedInvite:$,deleteExportedChatInvite:q}=(0,a.Sv)(),j=(0,i.sO)(null),[G,H,_]=(0,Oe.Z)(),z=(0,i.I4)((()=>{$({chatId:n,invite:N}),C(m.u1.EditInvite)}),[n,N,C,$]),V=(0,i.I4)((()=>{q({chatId:n,link:N.link}),C(m.u1.Invites),_()}),[n,_,N,q,C]),X=(0,i.I4)((e=>{T({query:e}),e.length&&ki(x)}),[x,T]),K=(0,i.I4)((e=>{B({query:e})}),[B]),W=(0,i.I4)((e=>{A({query:e})}),[A]),Y=(0,i.I4)((()=>{F({userId:y})}),[F,y]),[J,Q]=(0,i.eJ)(!s);(0,i.d4)((()=>{setTimeout((()=>{Q(!s)}),300)}),[s]);const ee=(0,Fe.Z)(),te=o?p===m.vi.Profile?Ri.Profile:p===m.vi.SharedMedia?Ri.SharedMedia:p===m.vi.MemberList?Ri.MemberList:-1:r?Ri.Search:g?Ri.PollResults:d?Ri.StickerSearch:u?Ri.GifSearch:f?Ri.AddingMembers:c?v===m.u1.Initial?Ri.ManageInitial:v===m.u1.ChatPrivacyType?Ri.ManageChatPrivacyType:v===m.u1.Discussion?Ri.ManageDiscussion:v===m.u1.ChannelSubscribers?Ri.ManageChannelSubscribers:v===m.u1.GroupPermissions?Ri.ManageGroupPermissions:v===m.u1.ChatAdministrators?Ri.ManageChatAdministrators:v===m.u1.GroupRemovedUsers?Ri.ManageGroupRemovedUsers:v===m.u1.ChannelRemovedUsers?Ri.ManageChannelRemovedUsers:v===m.u1.GroupUserPermissionsCreate?Ri.ManageGroupUserPermissionsCreate:v===m.u1.GroupUserPermissions?Ri.ManageGroupUserPermissions:v===m.u1.GroupRecentActions?Ri.ManageGroupRecentActions:v===m.u1.ChatAdminRights?Ri.ManageGroupAdminRights:v===m.u1.ChatNewAdminRights?Ri.ManageGroupNewAdminRights:v===m.u1.GroupMembers?Ri.ManageGroupMembers:v===m.u1.Invites?Ri.ManageInvites:v===m.u1.EditInvite?Ri.ManageEditInvite:v===m.u1.GroupAddAdmins?Ri.ManageGroupAddAdmins:v===m.u1.Reactions?Ri.ManageReactions:v===m.u1.InviteInfo?Ri.ManageInviteInfo:v===m.u1.JoinRequests?Ri.ManageJoinRequests:void 0:l?Ri.Statistics:void 0,ne=null!==(t=(0,Tt.Z)(te,!0))&&void 0!==t?t:-1,ae=h.wB||te===Ri.SharedMedia||te===Ri.MemberList||te===Ri.AddingMembers||c,se=(0,fe.Z)("animated-close-icon",ae&&"state-back",(J||M)&&"no-transition");return i.ZP.createElement("div",{className:"RightHeader"},i.ZP.createElement(ze.Z,{className:"close-button",round:!0,color:"translucent",size:"smaller",onClick:P,ariaLabel:ee(ae?"Common.Back":"Common.Close")},i.ZP.createElement("div",{ref:j,className:se})),i.ZP.createElement(Ue.Z,{name:J||M?"none":"slide-fade",activeKey:ne},function(){if(-1!==ne)switch(ne){case Ri.PollResults:return i.ZP.createElement("h3",null,ee("PollResults"));case Ri.Search:return i.ZP.createElement(i.ZP.Fragment,null,i.ZP.createElement(Ve.Z,{parentContainerClassName:"RightSearch",value:b,onChange:X}),i.ZP.createElement(ze.Z,{round:!0,size:"smaller",color:"translucent",onClick:()=>U({selectedAt:(0,L._F)(Date.now())}),ariaLabel:"Search messages by date"},i.ZP.createElement("i",{className:"icon-calendar"})));case Ri.AddingMembers:return i.ZP.createElement("h3",null,ee(Z?"ChannelAddSubscribers":"GroupAddMembers"));case Ri.ManageInitial:return i.ZP.createElement("h3",null,ee("Edit"));case Ri.ManageChatPrivacyType:return i.ZP.createElement("h3",null,ee(Z?"ChannelTypeHeader":"GroupTypeHeader"));case Ri.ManageDiscussion:return i.ZP.createElement("h3",null,ee("Discussion"));case Ri.ManageChatAdministrators:return i.ZP.createElement("h3",null,ee("ChannelAdministrators"));case Ri.ManageGroupRecentActions:return i.ZP.createElement("h3",null,ee("Group.Info.AdminLog"));case Ri.ManageGroupAdminRights:return i.ZP.createElement("h3",null,ee("EditAdminRights"));case Ri.ManageGroupNewAdminRights:return i.ZP.createElement("h3",null,ee("SetAsAdmin"));case Ri.ManageGroupPermissions:return i.ZP.createElement("h3",null,ee("ChannelPermissions"));case Ri.ManageGroupRemovedUsers:return i.ZP.createElement("h3",null,ee("BlockedUsers"));case Ri.ManageChannelRemovedUsers:return i.ZP.createElement("h3",null,ee("ChannelBlockedUsers"));case Ri.ManageGroupUserPermissionsCreate:return i.ZP.createElement("h3",null,ee("ChannelAddException"));case Ri.ManageGroupUserPermissions:return i.ZP.createElement("h3",null,ee("UserRestrictions"));case Ri.ManageInvites:return i.ZP.createElement("h3",null,ee("lng_group_invite_title"));case Ri.ManageEditInvite:return i.ZP.createElement("h3",null,ee(k?"EditLink":"NewLink"));case Ri.ManageInviteInfo:return i.ZP.createElement(i.ZP.Fragment,null,i.ZP.createElement("h3",null,ee("InviteLink")),i.ZP.createElement("section",{className:"tools"},N&&!N.isRevoked&&i.ZP.createElement(ze.Z,{round:!0,color:"translucent",size:"smaller",ariaLabel:ee("Edit"),onClick:z},i.ZP.createElement("i",{className:"icon-edit"})),N&&N.isRevoked&&i.ZP.createElement(i.ZP.Fragment,null,i.ZP.createElement(ze.Z,{round:!0,color:"danger",size:"smaller",ariaLabel:ee("Delete"),onClick:H},i.ZP.createElement("i",{className:"icon-delete"})),i.ZP.createElement($t.Z,{isOpen:G,onClose:_,title:ee("DeleteLink"),text:ee("DeleteLinkHelp"),confirmIsDestructive:!0,confirmLabel:ee("Delete"),confirmHandler:V}))));case Ri.ManageJoinRequests:return i.ZP.createElement("h3",null,ee(Z?"SubscribeRequests":"MemberRequests"));case Ri.ManageGroupAddAdmins:return i.ZP.createElement("h3",null,ee("Channel.Management.AddModerator"));case Ri.StickerSearch:return i.ZP.createElement(Ve.Z,{value:S,placeholder:ee("SearchStickersHint"),autoFocusSearch:!0,onChange:K});case Ri.GifSearch:return i.ZP.createElement(Ve.Z,{value:E,placeholder:ee("SearchGifsTitle"),autoFocusSearch:!0,onChange:W});case Ri.Statistics:return i.ZP.createElement("h3",null,ee("Statistics"));case Ri.SharedMedia:return i.ZP.createElement("h3",null,ee("SharedMedia"));case Ri.ManageChannelSubscribers:return i.ZP.createElement("h3",null,ee("ChannelSubscribers"));case Ri.MemberList:case Ri.ManageGroupMembers:return i.ZP.createElement("h3",null,ee("GroupMembers"));case Ri.ManageReactions:return i.ZP.createElement("h3",null,ee("Reactions"));default:return i.ZP.createElement(i.ZP.Fragment,null,i.ZP.createElement("h3",null,"Profile"),i.ZP.createElement("section",{className:"tools"},I&&i.ZP.createElement(ze.Z,{round:!0,color:"translucent",size:"smaller",ariaLabel:ee("AddContact"),onClick:Y},i.ZP.createElement("i",{className:"icon-add-user"})),w&&i.ZP.createElement(ze.Z,{round:!0,color:"translucent",size:"smaller",ariaLabel:ee("Edit"),onClick:O},i.ZP.createElement("i",{className:"icon-edit"})),R&&i.ZP.createElement(ze.Z,{round:!0,color:"translucent",size:"smaller",ariaLabel:ee("Statistics"),onClick:D},i.ZP.createElement("i",{className:"icon-stats"}))))}}()))})));var Ti=n(91);var Bi=n(7407);function Ai(e,t,n,a){const[i,o]=(0,Bi.Z)(n?t:void 0,a,void 0,s.Vk);return[i,o,!(!i||!a||i[0]===a[0])]}function xi(e,t,n,a,o,r){const c=(0,i.sO)();(0,Pe.Z)((()=>{t===e&&o&&r&&(c.current=(0,d.R5)(o,r,e))}),[o,r,t,e]);const[l,u]=(0,Bi.Z)(a?n:void 0,c.current,void 0,"media"===e?s.EN:s.pn);return[l,u,!(!l||!c.current||l[0]===c.current[0])]}const Li=(0,E.P2)((e=>e()),250,!1);let Oi=!1;var Ui=n(1273),Fi=n(1876),Di=n(787),$i=n(180),qi=n(3709),ji=n(5418),Gi=n(7262),Hi=n(1151),_i=n(2275);const zi=[{type:"media",title:"SharedMediaTab2"},{type:"documents",title:"SharedFilesTab2"},{type:"links",title:"SharedLinksTab2"},{type:"audio",title:"SharedMusicTab2"},{type:"voice",title:"SharedVoiceTab2"}];function Vi(e){return[`.shared-media-transition > div:only-child > .${e}-list > .scroll-item`,`.shared-media-transition > .Transition__slide--active > .${e}-list > .scroll-item`].join(", ")}const Xi=(0,i.X$)((0,a.c$)(((e,t)=>{var n,a;let{chatId:s}=t;const i=(0,c.Z1)(e,s),o=(0,c.Zw)(e,s),{currentType:r,resultsByType:l}=(0,c.we)(e)||{},{foundIds:u}=l&&r&&l[r]||{},{byId:m,statusesById:h}=e.users,{byId:g}=e.chats,f=i&&(0,d.Bf)(i),p=i&&(0,d.eA)(i),v=f||p&&(0,d.Nl)(i),I=null==i||null===(n=i.fullInfo)||void 0===n?void 0:n.members,y=v&&i&&i.fullInfo&&!i.fullInfo.canViewMembers,w=v&&i&&((0,d.VE)(i,"inviteUsers")||i.isCreator),Z=v&&i&&((0,d.VE)(i,"banUsers")||i.isCreator),P=(0,c.xs)(e,s);let C,b,S;return(0,d.YC)(s)&&(b=s,S=(0,c.dy)(e,b),C=S&&!S.isSelf&&!(0,d.cS)(S)),{theme:(0,c.Pu)(e),isChannel:p,resolvedUserId:b,chatMessages:o,foundIds:u,mediaSearchType:r,hasCommonChatsTab:C,hasMembersTab:v,areMembersHidden:y,canAddMembers:w,canDeleteMembers:Z,currentUserId:e.currentUserId,isRightColumnShown:(0,c.Jf)(e),isRestricted:null==i?void 0:i.isRestricted,lastSyncTime:e.lastSyncTime,serverTimeOffset:e.serverTimeOffset,activeDownloadIds:P,usersById:m,userStatusesById:h,chatsById:g,isChatProtected:null==i?void 0:i.isProtected,...v&&I&&{members:I},...C&&S&&{commonChatIds:null===(a=S.commonChats)||void 0===a?void 0:a.ids}}}))((e=>{let{chatId:t,profileState:n,onProfileStateChange:r,theme:c,isChannel:l,resolvedUserId:u,currentUserId:g,chatMessages:f,foundIds:p,mediaSearchType:v,hasCommonChatsTab:I,hasMembersTab:y,areMembersHidden:w,canAddMembers:Z,canDeleteMembers:P,commonChatIds:C,members:b,usersById:S,userStatusesById:E,chatsById:M,isRightColumnShown:k,isRestricted:R,lastSyncTime:N,activeDownloadIds:T,serverTimeOffset:B,isChatProtected:A}=e;const{setLocalMediaSearchType:x,loadMoreMembers:L,loadCommonChats:O,openChat:U,searchMediaMessagesLocal:F,openMediaViewer:D,openAudioPlayer:$,focusMessage:q,loadProfilePhotos:j,setNewChatMembersDialogState:G}=(0,a.Sv)(),H=(0,i.sO)(null),_=(0,i.sO)(null),z=(0,Fe.Z)(),[V,X]=(0,i.eJ)(0),[K,W]=(0,i.eJ)(),Y=(0,i.Ye)((()=>[...y?[{type:"members",title:l?"ChannelSubscribers":"GroupMembers"}]:[],...zi,...I?[{type:"commonChats",title:"SharedGroupsTab2"}]:[]]),[I,y,l]),J=Y[V].type,[Q,ee,te,ne]=function(e,t,n,a,s,o,r,c,l,u,m,h,g,f,p){let v=arguments.length>15&&void 0!==arguments[15]?arguments[15]:0;const I="members"!==s&&o?o:s,y=(0,i.Ye)((()=>{if(r&&l&&u)return(0,d.Z0)(r.map((e=>{let{userId:t}=e;return t})),l,u,void 0,v)}),[r,v,l,u]),w=(0,i.Ye)((()=>{if(c&&m)return(0,d.ih)(c,m,!0)}),[m,c]),[Z,P,C]=Ai(0,t,p,y),[b,S,E]=xi("media",I,a,p,h,g),[M,k,R]=xi("documents",I,a,p,h,g),[N,T,B]=xi("links",I,a,p,h,g),[A,x,L]=xi("audio",I,a,p,h,g),[O,U,F]=xi("voice",I,a,p,h,g),[D,$,q]=Ai(0,n,p,w);let j,G,H=!1;switch(I){case"members":j=Z,G=P,H=C;break;case"commonChats":j=D,G=$,H=q;break;case"media":j=b,G=S,H=E;break;case"documents":j=M,G=k,H=R;break;case"links":j=N,G=T,H=B;break;case"audio":j=A,G=x,H=L;break;case"voice":j=O,G=U,H=F}return[I,j,G,H]}(k,L,O,F,J,v,b,C,S,E,M,f,p,t,N,B),ae=Y.findIndex((e=>{let{type:t}=e;return t===Q})),{handleScroll:se}=function(e,t,n,a){(0,hn.Z)((n=>{let[s]=n;if(s&&s!==t){const n=e.current,s=n.querySelector(".TabList");n.scrollTop{Oi=!1}),350))}}),[t,a]),(0,hn.Z)((t=>{let[s]=t;if(n!==m.vi.Profile||n===s)return;const i=e.current;if(!i)return;const o=i.querySelector(".TabList");!o||o.offsetTop>i.scrollTop||(Oi=!0,(0,yn.Z)(i,i.firstElementChild,"start",void 0,2*i.offsetHeight),setTimeout((()=>{Oi=!1}),350),a(n))}),[n]);const s=(0,i.I4)((()=>{const n=e.current;if(!n)return;const s=n.querySelector(".TabList");if(!s)return;let i=m.vi.Profile;n.scrollTop>=s.offsetTop&&(i="members"===t?m.vi.MemberList:m.vi.SharedMedia),a(i)}),[e,a,t]);return(0,i.d4)((()=>{Oi||s()}),[s,t]),{handleScroll:(0,i.I4)((()=>{Oi||Li(s)}),[s])}}(H,J,n,r),{applyTransitionFix:ie,releaseTransitionFix:oe}=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:".Transition.shared-media-transition";(0,i.d4)((()=>{function n(){const n=e.current,a=n.querySelector(t),s=n.querySelector(".TabList");a&&s&&(a.style.minHeight=n.offsetHeight-s.offsetHeight+"px")}return n(),window.addEventListener("resize",n,!1),()=>{window.removeEventListener("resize",n,!1)}}),[e,t]);const n=(0,i.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]),a=(0,i.I4)((()=>{const t=e.current;t.style.overflowY="scroll",t.style.marginRight="0"}),[e]);return{applyTransitionFix:n,releaseTransitionFix:a}}(H),[re,ce]=(()=>{const[e,t]=(0,i.eJ)(!1);return[e,(0,i.I4)((()=>{t((e=>!e))}),[])]})(),{observe:le}=(0,Pn.S1)({rootRef:H,throttleMs:500}),de=(0,i.I4)((()=>{oe(),ce()}),[oe,ce]),ue=(0,i.I4)((()=>{G(m.WB.InProgress)}),[G]);(0,i.d4)((()=>{x({mediaType:J})}),[x,J]);const me=u||t;(0,i.d4)((()=>{N&&j({profileId:me})}),[j,me,N]);const he=(0,i.I4)((e=>{D({chatId:me,threadId:o._f,messageId:e,origin:m.bZ.SharedMedia})}),[me,D]),ge=(0,i.I4)((e=>{$({chatId:me,messageId:e})}),[me,$]),fe=(0,i.I4)((e=>{U({id:e})}),[U]),pe=(0,i.I4)((e=>{q({chatId:me,messageId:e})}),[me,q]),ve=(0,i.I4)((()=>{W(void 0)}),[]);let Ie;(0,i.d4)((()=>{if(_.current&&h.$b)return(0,tt.sf)(_.current,{selectorToPreventScroll:".Profile",onSwipe:(e,t)=>t===tt.eM.Left?(X(Math.min(V+1,Y.length-1)),!0):t===tt.eM.Right&&(X(Math.max(0,V-1)),!0)})}),[V,Y.length]);const ye="members"===Q||!y&&"media"===Q;ye?Ie=k?0:1e3:ee||(Ie=s.Y);const we=(0,ii.Z)([t,Q],Ie);return i.ZP.createElement(Ui.Z,{ref:H,className:"Profile custom-scroll",itemSelector:Vi(Q),items:we?ee:void 0,cacheBuster:re,sensitiveArea:s.qU,preloadBackwards:we?"members"===Q?s.Vk:s.EN:0,noScrollRestoreOnTop:!0,noFastList:!0,onLoadMore:te,onScroll:se},!ne&&function(e,t){return i.ZP.createElement("div",{className:"profile-info"},i.ZP.createElement(Di.Z,{userId:t||e}),i.ZP.createElement($i.Z,{chatOrUserId:t||e}))}(t,u),!R&&i.ZP.createElement("div",{className:"shared-media"},i.ZP.createElement(Ue.Z,{ref:_,name:z.isRtl?"slide-optimized-rtl":"slide-optimized",activeKey:ae,renderCount:Y.length,shouldRestoreHeight:!0,className:"shared-media-transition",onStart:ie,onStop:de},function(){if(!ee||!we||!f){const e=ye&&!we;return i.ZP.createElement("div",{className:"content empty-list"},!e&&i.ZP.createElement(Ye.Z,null))}if(!ee.length){let e;switch(Q){case"members":e=w?"You have no access to group members list.":"No members found";break;case"commonChats":e=z("NoGroupsInCommon");break;case"documents":e=z("lng_media_file_empty");break;case"links":e=z("lng_media_link_empty");break;case"audio":e=z("lng_media_song_empty");break;case"voice":e=z("lng_media_audio_empty");break;default:e=z("SharedMedia.EmptyTitle")}return i.ZP.createElement("div",{className:"content empty-list"},i.ZP.createElement(Gi.Z,{text:e}))}return i.ZP.createElement("div",{className:`content ${Q}-list`,dir:z.isRtl&&"media"===Q?"rtl":void 0,teactFastList:!0},"media"===Q?ee.map((e=>f[e]&&i.ZP.createElement(qi.Z,{key:e,message:f[e],isProtected:A||f[e].isProtected,observeIntersection:le,onClick:he}))):"documents"===Q?ee.map((e=>f[e]&&i.ZP.createElement(zn.Z,{key:e,message:f[e],withDate:!0,smaller:!0,className:"scroll-item",isDownloading:T.includes(e),observeIntersection:le,onDateClick:pe}))):"links"===Q?ee.map((e=>f[e]&&i.ZP.createElement(ji.Z,{key:e,message:f[e],isProtected:A||f[e].isProtected,observeIntersection:le,onMessageClick:pe}))):"audio"===Q?ee.map((e=>f[e]&&i.ZP.createElement(Vn.Z,{key:e,theme:c,message:f[e],origin:m.Cr.SharedMedia,date:f[e].date,lastSyncTime:N,className:"scroll-item",onPlay:ge,onDateClick:pe,isDownloading:T.includes(e)}))):"voice"===Q?ee.map((e=>f[e]&&i.ZP.createElement(Vn.Z,{key:e,theme:c,message:f[e],senderTitle:(0,Ti.F)(z,f[e],M,S),origin:m.Cr.SharedMedia,date:f[e].date,lastSyncTime:N,className:"scroll-item",onPlay:ge,onDateClick:pe,isDownloading:T.includes(e)}))):"members"===Q?ee.map(((e,t)=>{return i.ZP.createElement(Fi.Z,{key:e,teactOrderKey:t,className:"chat-item-clickable scroll-item small-icon",onClick:()=>fe(e),contextActions:(n=e,n!==g&&P?[{title:z("lng_context_remove_from_group"),icon:"stop",handler:()=>{W(n)}}]:void 0)},i.ZP.createElement(Bt.Z,{userId:e,forceShowSelf:!0}));var n})):"commonChats"===Q?ee.map(((e,t)=>i.ZP.createElement(Fi.Z,{key:e,teactOrderKey:t,className:"chat-item-clickable scroll-item small-icon",onClick:()=>U({id:e})},i.ZP.createElement(At.Z,{chatId:e})))):void 0)}()),i.ZP.createElement(nt.Z,{big:!0,activeTab:V,tabs:Y,onSwitchTab:X})),Z&&i.ZP.createElement(Hi.Z,{isShown:"members"===Q,onClick:ue,ariaLabel:z("lng_channel_add_users")},i.ZP.createElement("i",{className:"icon-add-user-filled"})),P&&i.ZP.createElement(_i.Z,{isOpen:Boolean(K),userId:K,onClose:ve}))}))),Ki=(0,i.X$)((e=>{const t=(0,ot.Z)(it.gl.Extra,"RightSearch");return t?i.ZP.createElement(t,e):i.ZP.createElement(rt.Z,null)})),Wi=(0,i.X$)((e=>{const t=(0,ot.Z)(it.gl.Extra,"Management");return t?i.ZP.createElement(t,e):i.ZP.createElement(rt.Z,null)})),Yi=e=>{const t=(0,ot.Z)(it.gl.Extra,"Statistics");return t?i.ZP.createElement(t,e):i.ZP.createElement(rt.Z,null)},Ji=(0,i.X$)((()=>{const e=(0,ot.Z)(it.gl.Extra,"StickerSearch");return e?i.ZP.createElement(e,null):i.ZP.createElement(rt.Z,null)})),Qi=(0,i.X$)((()=>{const e=(0,ot.Z)(it.gl.Extra,"GifSearch");return e?i.ZP.createElement(e,null):i.ZP.createElement(rt.Z,null)})),eo=(0,i.X$)((()=>{const e=(0,ot.Z)(it.gl.Extra,"PollResults");return e?i.ZP.createElement(e,null):i.ZP.createElement(rt.Z,null)}));var to=n(1820);const no=(0,i.X$)((0,a.c$)(((e,t)=>{var n;let{chatId:a}=t;const s=(0,c.Z1)(e,a),{userIds:i}=e.contactList||{},{byId:o}=e.chats,{currentUserId:r,newChatMembersProgress:l,connectionState:u}=e,h=s&&(0,d.eA)(s),{query:g,fetchingStatus:f,globalUserIds:p,localUserIds:v}=e.userSearch;return{isChannel:h,members:null==s||null===(n=s.fullInfo)||void 0===n?void 0:n.members,currentUserId:r,chatsById:o,localContactIds:i,searchQuery:g,isSearching:f,isLoading:l===m.WB.Loading,globalUserIds:p,localUserIds:v,connectionState:u}}))((e=>{let{isChannel:t,connectionState:n,members:s,onNextStep:o,currentUserId:r,chatsById:c,localContactIds:l,isLoading:u,searchQuery:m,isSearching:h,localUserIds:f,globalUserIds:p,onClose:v,isActive:I}=e;const{setUserSearchQuery:y,loadContactList:w}=(0,a.Sv)(),Z=(0,Fe.Z)(),[P,C]=(0,i.eJ)([]),b=(0,Mt.Z)(P)===P;(0,i.d4)((()=>{I&&"connectionStateReady"===n&&w()}),[n,I,w]),(0,Me.ZP)(I,v);const S=(0,i.Ye)((()=>s?s.map((e=>e.userId)):[]),[s]),E=(0,i.I4)((e=>{y({query:e})}),[y]),M=(0,i.Ye)((()=>{const e=(0,a.Rd)().users.byId,n=l?(0,d.kK)(l,e,m):[];return(0,d.ih)((0,g.Tw)([...n,...f||[],...p||[]]).filter((n=>{const a=e[n];return!S.includes(n)&&n!==r&&(!a||!(0,d.cS)(a)||!t&&a.canBeInvitedToGroup)})),c)}),[l,c,m,f,p,r,S,t]),k=(0,i.I4)((()=>{P.length&&(y({query:""}),o(P))}),[P,y,o]);return i.ZP.createElement("div",{className:"AddChatMembers"},i.ZP.createElement("div",{className:"AddChatMembers-inner"},i.ZP.createElement(to.Z,{itemIds:M,selectedIds:P,filterValue:m,filterPlaceholder:Z("lng_channel_add_users"),searchInputId:"new-members-picker-search",isLoading:h,onSelectedIdsChange:C,onFilterChange:E,noScrollRestore:b}),i.ZP.createElement(Hi.Z,{isShown:Boolean(P.length),disabled:u,ariaLabel:Z("lng_channel_add_users"),onClick:k},u?i.ZP.createElement(Ye.Z,{color:"white"}):i.ZP.createElement("i",{className:"icon-arrow-right"}))))}))),ao=Object.keys(m.qt).length/2,so=Object.keys(m.u1).length/2;function io(){const e=document.querySelector(".RightHeader .SearchInput input");e&&e.blur()}const oo=(0,i.X$)((0,a.c$)((e=>{var t;const{chatId:n,threadId:a}=(0,c.Bt)(e)||{},s=(0,c.g4)(e),i=n?null===(t=e.management.byChatId[n])||void 0===t?void 0:t.nextScreen:void 0;return{contentKey:(0,c.Wq)(e),chatId:n,threadId:a,isChatSelected:Boolean(n&&s),shouldSkipHistoryAnimations:e.shouldSkipHistoryAnimations,nextManagementScreen:i}}))((e=>{var t;let{contentKey:n,chatId:o,threadId:r,isChatSelected:c,shouldSkipHistoryAnimations:l,nextManagementScreen:d}=e;const{toggleChatInfo:u,toggleManagement:h,closeLocalTextSearch:g,setStickerSearchQuery:f,setGifSearchQuery:p,closePollResults:v,addChatMembers:I,setNewChatMembersDialogState:y,setEditingExportedInvite:w,toggleStatistics:Z,setOpenedInviteInfo:P,requestNextManagementScreen:C}=(0,a.Sv)(),{width:b}=St(),[S,E]=(0,i.eJ)(m.vi.Profile),[M,k]=(0,i.eJ)(m.u1.Initial),[R,N]=(0,i.eJ)(),[T,B]=(0,i.eJ)(),A=S!==m.vi.Profile,x=void 0!==n,L=n===m.qt.ChatInfo,O=n===m.qt.Search,U=n===m.qt.Management,F=n===m.qt.Statistics,D=n===m.qt.StickerSearch,$=n===m.qt.GifSearch,q=n===m.qt.PollResults,j=n===m.qt.AddingMembers,G=b<=s._m,[H,_]=(0,i.eJ)(!x),z=null!==(t=(0,Tt.Z)(n,!0,!c))&&void 0!==t?t:-1,V=(0,i.I4)((function(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];switch(n){case m.qt.AddingMembers:y(m.WB.Closed);break;case m.qt.ChatInfo:if(A&&e){E(m.vi.Profile);break}u(void 0,{forceSyncOnIOs:!0});break;case m.qt.Management:switch(M){case m.u1.Initial:h();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:case m.u1.Invites:case m.u1.Reactions:case m.u1.JoinRequests:case m.u1.ChannelRemovedUsers:k(m.u1.Initial);break;case m.u1.GroupUserPermissionsCreate:case m.u1.GroupRemovedUsers:case m.u1.GroupUserPermissions:k(m.u1.GroupPermissions),N(void 0),B(void 0);break;case m.u1.ChatAdminRights:case m.u1.ChatNewAdminRights:case m.u1.GroupAddAdmins:case m.u1.GroupRecentActions:k(m.u1.ChatAdministrators);break;case m.u1.EditInvite:case m.u1.InviteInfo:k(m.u1.Invites),P({invite:void 0}),w({chatId:o,invite:void 0})}break;case m.qt.Statistics:Z();break;case m.qt.Search:io(),g();break;case m.qt.StickerSearch:io(),f({query:void 0});break;case m.qt.GifSearch:io(),p({query:void 0});break;case m.qt.PollResults:v()}}),[n,A,u,v,y,M,h,g,f,p,w,o,P,Z]),X=(0,i.I4)(((e,t)=>{N(e),B(t)}),[]),K=(0,i.I4)((e=>{I({chatId:o,memberIds:e})}),[I,o]);function W(e){if(-1!==z)switch(z){case m.qt.AddingMembers:return i.ZP.createElement(no,{key:o,chatId:o,isActive:x&&e,onNextStep:K,onClose:V});case m.qt.ChatInfo:return i.ZP.createElement(Xi,{key:o,chatId:o,profileState:S,onProfileStateChange:E});case m.qt.Search:return i.ZP.createElement(Ki,{chatId:o,threadId:r,onClose:V,isActive:x&&e});case m.qt.Management:return i.ZP.createElement(Wi,{key:o,chatId:o,currentScreen:M,isPromotedByCurrentUser:T,selectedChatMemberId:R,isActive:x&&e,onScreenSelect:k,onChatMemberSelect:X,onClose:V});case m.qt.Statistics:return i.ZP.createElement(Yi,{chatId:o,isActive:x&&e});case m.qt.StickerSearch:return i.ZP.createElement(Ji,{onClose:V,isActive:x&&e});case m.qt.GifSearch:return i.ZP.createElement(Qi,{onClose:V,isActive:x&&e});case m.qt.PollResults:return i.ZP.createElement(eo,{onClose:V,isActive:x&&e})}}return(0,i.d4)((()=>x?(0,Ae.Z)(V):void 0),[x,V]),(0,i.d4)((()=>{setTimeout((()=>{_(!x)}),300)}),[x]),(0,i.d4)((()=>{d&&(k(d),C(void 0))}),[d,C]),(0,i.d4)((()=>{x&&G&&V()}),[G]),(0,mn.Z)((e=>{let[t]=e;t!==o&&(E(m.vi.Profile),k(m.u1.Initial))}),[o]),(0,Me.ZP)(c&&(n===m.qt.ChatInfo||n===m.qt.Management||n===m.qt.AddingMembers),(()=>V(!1)),u),i.ZP.createElement("div",{id:"RightColumn-wrapper",className:c?void 0:"is-hidden"},G&&i.ZP.createElement("div",{className:"overlay-backdrop",onClick:V}),i.ZP.createElement("div",{id:"RightColumn"},i.ZP.createElement(Ni,{chatId:o,isColumnOpen:x,isProfile:L,isSearch:O,isManagement:U,isStatistics:F,isStickerSearch:D,isGifSearch:$,isPollResults:q,isAddingChatMembers:j,profileState:S,managementScreen:M,onClose:V,shouldSkipAnimation:H||l,onScreenSelect:k}),i.ZP.createElement(Ue.Z,{name:H||l?"none":"zoom-fade",renderCount:ao+so,activeKey:U?ao+M:z,shouldCleanup:!0},W)))}))),ro=(0,i.X$)((e=>{let{isOpen:t}=e;const n=(0,ot.Z)(it.gl.Extra,"MediaViewer",!t);return n?i.ZP.createElement(n,null):void 0}));function co(e,t){const n=document.createElement("a");n.href=e,n.download=t;try{n.click()}catch(e){console.error(e)}}const lo=new Set,uo=(0,i.X$)((0,a.c$)((e=>({activeDownloads:e.activeDownloads.byChatId,messages:e.messages.byChatId})))((e=>{let{activeDownloads:t,messages:n}=e;const{cancelMessageMediaDownload:s}=(0,a.Sv)();(0,i.d4)((()=>{Object.entries(t).forEach((e=>{let[t,a]=e;a.map((e=>n[Number(t)].byId[e])).forEach((e=>{const t=(0,d.Ti)(e,"download");if(t){if(!lo.has(t)){const n=X.UV(t);if(n)return lo.delete(t),co(n,(0,d.w6)(e)),void s({message:e});X.he(t,o.IU.BlobUrl,!0).then((n=>{lo.delete(t),n&&co(n,(0,d.w6)(e)),s({message:e})})),lo.add(t)}}else s({message:e})}))}))}),[s,n,t])}))),mo=(0,i.X$)((e=>{let{isOpen:t}=e;const n=(0,ot.Z)(it.gl.Extra,"Notifications",!t);return n?i.ZP.createElement(n,null):void 0})),ho=(0,i.X$)((e=>{let{isOpen:t}=e;const n=(0,ot.Z)(it.gl.Extra,"Dialogs",!t);return n?i.ZP.createElement(n,null):void 0})),go=(0,i.X$)((e=>{const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"ForwardPicker",!t);return n?i.ZP.createElement(n,e):void 0})),fo=(0,i.X$)((e=>{const{url:t}=e,n=(0,ot.Z)(it.gl.Extra,"SafeLinkModal",!t);return n?i.ZP.createElement(n,e):void 0})),po=(0,i.X$)((e=>{const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"HistoryCalendar",!t);return n?i.ZP.createElement(n,e):void 0})),vo=(0,i.X$)((e=>{const{groupCallId:t}=e,n=(0,ot.Z)(it.gl.Calls,"GroupCall",!t);return n?i.ZP.createElement(n,e):void 0})),Io=(0,i.X$)((e=>{const{groupCallId:t}=e,n=(0,ot.Z)(it.gl.Calls,"ActiveCallHeader",!t);return n?i.ZP.createElement(n,null):void 0})),yo=(0,i.X$)((e=>{let{isOpen:t}=e;const n=(0,ot.Z)(it.gl.Calls,"CallFallbackConfirm",!t);return n?i.ZP.createElement(n,{isOpen:t}):void 0})),wo=(0,i.X$)((e=>{const{isOpen:t}=e,n=(0,ot.Z)(it.gl.Extra,"NewContactModal",!t);return n?i.ZP.createElement(n,e):void 0}));let Zo,Po=!1;function Co(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 So=(0,i.X$)((0,a.c$)((e=>{var t,n;const{settings:{byKey:{animationLevel:a,language:s,wasTimeFormatSetManually:i}}}=e,{chatId:o,messageId:r}=e.audioPlayer,l=o&&r?(0,c.hj)(e,o,r):void 0;return{connectionState:e.connectionState,authState:e.authState,lastSyncTime:e.lastSyncTime,isLeftColumnShown:e.isLeftColumnShown,isRightColumnShown:(0,c.Jf)(e),isMediaViewerOpen:(0,c.zQ)(e),isForwardModalOpen:(0,c.Ev)(e),hasNotifications:Boolean(e.notifications.length),hasDialogs:Boolean(e.dialogs.length),audioMessage:l,safeLinkModalUrl:e.safeLinkModalUrl,isHistoryCalendarOpen:Boolean(e.historyCalendarSelectedAt),shouldSkipHistoryAnimations:e.shouldSkipHistoryAnimations,openedStickerSetShortName:e.openedStickerSetShortName,isServiceChatReady:(0,c.UW)(e),activeGroupCallId:e.groupCalls.activeGroupCallId,animationLevel:a,language:s,wasTimeFormatSetManually:i,isCallFallbackConfirmOpen:Boolean(e.groupCalls.isFallbackConfirmOpen),addedSetIds:e.stickers.added.setIds,newContactUserId:null===(t=e.newContact)||void 0===t?void 0:t.userId,newContactByPhoneNumber:null===(n=e.newContact)||void 0===n?void 0:n.isByPhoneNumber}}))((e=>{let{connectionState:t,authState:n,lastSyncTime:o,isLeftColumnShown:r,isRightColumnShown:c,isMediaViewerOpen:l,isForwardModalOpen:d,hasNotifications:u,hasDialogs:m,audioMessage:g,activeGroupCallId:f,safeLinkModalUrl:p,isHistoryCalendarOpen:v,shouldSkipHistoryAnimations:I,openedStickerSetShortName:y,isServiceChatReady:w,animationLevel:Z,language:P,wasTimeFormatSetManually:C,isCallFallbackConfirmOpen:b,addedSetIds:S,newContactUserId:M,newContactByPhoneNumber:k}=e;const{sync:R,loadAnimatedEmojis:N,loadNotificationSettings:T,loadNotificationExceptions:B,updateIsOnline:A,loadTopInlineBots:x,loadEmojiKeywords:L,loadCountryList:O,loadAvailableReactions:U,loadStickerSets:F,loadAddedStickers:$,loadFavoriteStickers:q,ensureTimeFormat:j,openStickerSetShortName:G,checkVersionNotification:H,loadAppConfig:_}=(0,a.Sv)();s.eM&&!Po&&(Po=!0,console.log(">>> RENDER MAIN")),(0,i.d4)((()=>{"connectionStateReady"===t&&"authorizationStateReady"===n&&R()}),[t,n,R]),(0,i.d4)((()=>{o&&(A(!0),_(),U(),N(),T(),B(),x(),L({language:s.pR}))}),[o,N,L,B,T,x,A,U,_]),(0,i.d4)((()=>{o&&(P!==s.pR&&L({language:P}),O({langCode:P}))}),[P,o,O,L]),(0,i.d4)((()=>{o&&(S?$():(F(),q()))}),[o,S,F,q,$]),(0,i.d4)((()=>{o&&w&&H()}),[o,w,H]),(0,i.d4)((()=>{o&&!C&&j()}),[o,C,j]),(0,i.d4)((()=>{o&&Me.Oy.startsWith("#?tgaddr=")&&(0,ve.o)(decodeURIComponent(Me.Oy.substr("#?tgaddr=".length)))}),[o]),(0,i.d4)((()=>{if(f)return Q.Z.disableRefresh(),()=>{Q.Z.enableRefresh()}}),[f]);const{transitionClassNames:z}=(0,ye.Z)(!r,void 0,!0,void 0,I),{transitionClassNames:V}=(0,ye.Z)(c,void 0,!0,void 0,I),X=(0,fe.Z)(z.replace(/([\w-]+)/g,"middle-column-$1"),V.replace(/([\w-]+)/g,"right-column-$1"),I&&"history-animation-disabled");(0,Pe.Z)((e=>{let[t]=e;if(void 0===t||0===Z)return;const n=(0,ge.YW)();(0,pe.L)(document.getElementById("MiddleColumn"),n)}),[r]),(0,Pe.Z)((e=>{let[t]=e;if(void 0===t||0===Z)return;(0,E.T2)((()=>{document.body.classList.add("animating-right-column")}));const n=(0,ge.YW)();(0,pe.L)(document.getElementById("RightColumn"),(()=>{n(),(0,E.T2)((()=>{document.body.classList.remove("animating-right-column")}))}))}),[c]);const K=(0,i.I4)((()=>{A(!1);const e=(0,D.xW)();let t=0;clearInterval(Zo),Zo=window.setInterval((()=>{if(document.title.includes(s.ou))Co(!1);else{if(t%2==0){const t=(0,D.xW)()-e;t>0&&(bo(`${t} notification${t>1?"s":""}`),Co(!0))}else bo(s.Ti),Co(!1);t++}}),1e3)}),[A]),W=(0,i.I4)((()=>{A(!0),clearInterval(Zo),Zo=void 0,document.title.includes(s.ou)||bo(s.Ti),Co(!1)}),[A]),Y=(0,i.I4)((()=>{G({stickerSetShortName:void 0})}),[G]);return(0,we.Z)(K,W),Ze(K),function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];(0,i.d4)((()=>{if(h.$b){if(!e)return null==Ce||Ce.setAttribute("content",be),h.cj&&!h.fl&&document.addEventListener("gesturestart",Ee),()=>{null==Ce||Ce.setAttribute("content","width=device-width, initial-scale=1, shrink-to-fit=no"),h.cj&&!h.fl&&document.removeEventListener("gesturestart",Ee)};null==Ce||Ce.setAttribute("content",Se)}}),[e])}(l),i.ZP.createElement("div",{id:"Main",className:X,onDrop:Ie.Z,onDragOver:Ie.Z},i.ZP.createElement(wt,null),i.ZP.createElement(Mi,null),i.ZP.createElement(oo,null),i.ZP.createElement(ro,{isOpen:l}),i.ZP.createElement(go,{isOpen:d}),i.ZP.createElement(mo,{isOpen:u}),i.ZP.createElement(ho,{isOpen:m}),g&&i.ZP.createElement(sn,{key:g.id,message:g,noUi:!0}),i.ZP.createElement(fo,{url:p}),i.ZP.createElement(po,{isOpen:v}),i.ZP.createElement(ke.Z,{isOpen:Boolean(y),onClose:Y,stickerSetShortName:y}),f&&i.ZP.createElement(i.ZP.Fragment,null,i.ZP.createElement(vo,{groupCallId:f}),i.ZP.createElement(Io,{groupCallId:f})),i.ZP.createElement(wo,{isOpen:Boolean(M||k),userId:M,isByPhoneNumber:k}),i.ZP.createElement(uo,null),i.ZP.createElement(yo,{isOpen:b}),i.ZP.createElement(Be,{isForAppBadge:!0}))})));s.eM&&console.log(">>> FINISH LOAD MAIN BUNDLE"),(0,a.Rd)().connectionState||(0,a.Sv)().initApi()},8973:(e,t,n)=>{e.exports=n.p+"encoderWorker.min.8ea62f6317fbac7d4558..js"},8226:(e,t,n)=>{e.exports=n.p+"map-pin.7b3c3e60ee24795e4bd2..svg"},4524:(e,t,n)=>{e.exports=n.p+"telegram-logo-filled.67469f6dc5e301e8e0bd..svg"},257:e=>{e.exports='**Telegram Web Z was updated to version 1.38**\n\n👏 **Harder**\n• See interactive statistics for groups you manage.\n• Adjust volume and playback speed with new controls in the Media Viewer.\n• Save GIFs sent by other users.\n• Schedule stickers and GIFs or send them silently – right-click on desktop or long-press on mobile.\n• "Report Spam and Leave" button added for unknown channels.\n• Drafts now save when editing messages.\n• Set a custom name or include a phone number when adding contacts.\n• New contacts can now be added from the Contacts page.\n• Click to copy code blocks to your clipboard.\n\n🤩 **Better**\n• Background pattern added for Night Mode.\n• New message drafts are restored after editing another message.\n• Updated font for Persian language (Vazirmatn 32.1).\n• More and more UX improvements.\n\n🚀 **Faster**\n• Optimized multiple algorithms, accelerated rendering.\n\n💪 **Stronger**\n• Fixed notification sounds for reactions in muted chats.\n• Fixed chat participants sometimes being inaccurate.\n• Fixed seeking position for audio tracks.\n• Fixed unintended playback of videos in Media Viewer caused by key.\n• Fixed missing QR codes after canceling login on another device.\n'}}]); -//# sourceMappingURL=616.dfb0d60d06da102bbad4.js.map \ No newline at end of file +//# sourceMappingURL=616.421a1d053cdd90ce3d23.js.map \ No newline at end of file diff --git a/dist/616.dfb0d60d06da102bbad4.js.map b/dist/616.421a1d053cdd90ce3d23.js.map similarity index 99% rename from dist/616.dfb0d60d06da102bbad4.js.map rename to dist/616.421a1d053cdd90ce3d23.js.map index e488af82..98002e65 100644 --- a/dist/616.dfb0d60d06da102bbad4.js.map +++ b/dist/616.421a1d053cdd90ce3d23.js.map @@ -1 +1 @@ -{"version":3,"file":"616.dfb0d60d06da102bbad4.js","mappings":"gOAoDO,SAASA,EAAqBC,GACnC,MAAM,OAAEC,EAAF,SAAUC,IAAaC,EAAAA,EAAAA,IAAyBH,IAAW,GACjE,OAAKC,GAAWC,GAIhBF,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AAD,CAAkBM,YAAaN,KAGnC,mBAAC,GAAD,CACEgG,OAAQ19B,QAAQ2tG,GAAoBC,GACpCpmG,OAAQmmG,EACRjmG,gBAAiBkmG,IAEnB,mBAAC,GAAD,MACA,mBAAC,GAAD,CAAqBlwE,OAAQ+vE,IAC7B,mBAAC,GAAD,CAAaz0E,eAAa,SCjV5Bzb,EAAAA,IAEFC,QAAQC,IAAI,gCAGT3b,EAAAA,EAAAA,MAAY01B,kBACf1c,EAAAA,EAAAA,MAAa80F,W","sources":["webpack://telegram-t/./src/global/actions/ui/localSearch.ts","webpack://telegram-t/./src/global/actions/ui/chats.ts","webpack://telegram-t/./src/global/actions/ui/messages.ts","webpack://telegram-t/./src/global/actions/ui/globalSearch.ts","webpack://telegram-t/./src/global/actions/ui/stickerSearch.ts","webpack://telegram-t/./src/global/actions/ui/users.ts","webpack://telegram-t/./src/global/actions/ui/misc.ts","webpack://telegram-t/./src/global/actions/ui/payments.ts","webpack://telegram-t/./src/global/actions/ui/mediaViewer.ts","webpack://telegram-t/./src/global/actions/api/messages.ts","webpack://telegram-t/./src/global/actions/api/symbols.ts","webpack://telegram-t/./src/global/actions/api/globalSearch.ts","webpack://telegram-t/./src/global/actions/api/localSearch.ts","webpack://telegram-t/./src/global/actions/api/management.ts","webpack://telegram-t/./src/global/actions/api/sync.ts","webpack://telegram-t/./src/global/actions/api/users.ts","webpack://telegram-t/./src/global/reducers/bots.ts","webpack://telegram-t/./src/global/actions/api/bots.ts","webpack://telegram-t/./src/global/actions/api/twoFaSettings.ts","webpack://telegram-t/./src/global/actions/api/payments.ts","webpack://telegram-t/./src/util/requestQuery.ts","webpack://telegram-t/./src/components/middle/helpers/calculateMiddleFooterTransforms.ts","webpack://telegram-t/./src/global/reducers/reactions.ts","webpack://telegram-t/./src/global/actions/api/reactions.ts","webpack://telegram-t/./src/global/actions/api/statistics.ts","webpack://telegram-t/./src/util/areDeepEqual.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/chats.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/messages.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/users.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/symbols.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/misc.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/settings.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/twoFaSettings.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/calls.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/payments.ts","webpack://telegram-t/./src/hooks/useBeforeUnload.ts","webpack://telegram-t/./src/hooks/usePreventPinchZoomGesture.ts","webpack://telegram-t/./src/components/common/UnreadCounter.tsx","webpack://telegram-t/./src/hooks/useConnectionStatus.ts","webpack://telegram-t/./src/hooks/useBrowserOnline.ts","webpack://telegram-t/./src/components/left/ConnectionStatusOverlay.tsx","webpack://telegram-t/./src/components/left/main/LeftMainHeader.tsx","webpack://telegram-t/./src/components/left/main/ChatFolders.tsx","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/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/ChatReportPanel.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/hooks/useOuterHandlers.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/ReactionAnimatedEmoji.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/util/map.ts","webpack://telegram-t/./src/components/ui/Skeleton.tsx","webpack://telegram-t/./src/components/middle/message/Location.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/ReactionButton.tsx","webpack://telegram-t/./src/components/middle/message/Reactions.tsx","webpack://telegram-t/./src/components/common/LocalAnimatedEmoji.tsx","webpack://telegram-t/./src/components/middle/message/Message.tsx","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/hooks/useNativeCopySelectedMessages.ts","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/util/insertHtmlInSelection.ts","webpack://telegram-t/./src/components/middle/composer/helpers/applyIosAutoCapitalizationFix.ts","webpack://telegram-t/./src/util/voiceRecording.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useClipboardPaste.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useDraft.ts","webpack://telegram-t/./src/hooks/useDebouncedMemo.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.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/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/middle/composer/SendAsMenu.async.tsx","webpack://telegram-t/./src/components/middle/composer/Composer.tsx","webpack://telegram-t/./src/components/middle/composer/hooks/useVoiceRecording.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useStickerTooltip.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/EmojiInteractionAnimation.async.tsx","webpack://telegram-t/./src/components/middle/ReactorListModal.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/statistics/Statistics.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/NewContactModal.async.tsx","webpack://telegram-t/./src/components/main/Main.tsx","webpack://telegram-t/./src/bundles/main.ts"],"sourcesContent":["import { addActionHandler } from '../../index';\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 '../../types';\n\naddActionHandler('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\naddActionHandler('closeLocalTextSearch', closeLocalTextSearch);\n\naddActionHandler('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\naddActionHandler('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 { addActionHandler, setGlobal } from '../../index';\n\nimport { MAIN_THREAD_ID } from '../../../api/types';\n\nimport {\n exitMessageSelectMode, replaceThreadParam, updateCurrentMessageList,\n} from '../../reducers';\nimport { selectCurrentMessageList } from '../../selectors';\nimport { closeLocalTextSearch } from './localSearch';\n\naddActionHandler('openChat', (global, actions, payload) => {\n const {\n id,\n threadId = MAIN_THREAD_ID,\n type = 'thread',\n 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 if (id) {\n global = replaceThreadParam(global, id, threadId, 'replyStack', []);\n }\n\n global = exitMessageSelectMode(global);\n global = closeLocalTextSearch(global);\n\n global = {\n ...global,\n isStatisticsShown: false,\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\naddActionHandler('openPreviousChat', (global) => {\n return updateCurrentMessageList(global, undefined);\n});\n\naddActionHandler('openChatWithInfo', (global, actions, payload) => {\n setGlobal({\n ...global,\n isChatInfoShown: true,\n });\n\n actions.openChat(payload);\n});\n\naddActionHandler('resetChatCreation', (global) => {\n return {\n ...global,\n chatCreation: undefined,\n };\n});\n\naddActionHandler('setNewChatMembersDialogState', (global, actions, payload) => {\n return {\n ...global,\n newChatMembersProgress: payload,\n };\n});\n\naddActionHandler('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 { addActionHandler, getGlobal, setGlobal } from '../../index';\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 selectSender,\n} from '../../selectors';\nimport { findLast } from '../../../util/iteratees';\nimport { getServerTime } from '../../../util/serverTime';\n\nimport versionNotification from '../../../versionNotification.txt';\nimport parseMessageInput from '../../../util/parseMessageInput';\nimport { getMessageSummaryText, getSenderTitle } from '../../helpers';\nimport * as langProvider from '../../../util/langProvider';\nimport { copyTextToClipboard } from '../../../util/clipboard';\nimport { GlobalState } from '../../types';\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\naddActionHandler('setScrollOffset', (global, actions, payload) => {\n const { chatId, threadId, scrollOffset } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'scrollOffset', scrollOffset);\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('setEditingDraft', (global, actions, payload) => {\n const {\n text, chatId, threadId, type,\n } = payload;\n\n const paramName = type === 'scheduled' ? 'editingScheduledDraft' : 'editingDraft';\n\n return replaceThreadParam(global, chatId, threadId, paramName, text);\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('openPollResults', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n\n const shouldOpenInstantly = selectIsRightColumnShown(global);\n\n if (!shouldOpenInstantly) {\n window.setTimeout(() => {\n global = getGlobal();\n\n setGlobal({\n ...global,\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 return {\n ...global,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n };\n }\n\n return undefined;\n});\n\naddActionHandler('closePollResults', (global) => {\n return {\n ...global,\n pollResults: {},\n };\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('exitForwardMode', (global) => {\n setGlobal({\n ...global,\n forwardMessages: {},\n });\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('disableContextMenuHint', (global) => {\n if (!global.shouldShowContextMenuHint) {\n return undefined;\n }\n\n return {\n ...global,\n shouldShowContextMenuHint: false,\n };\n});\n\naddActionHandler('exitMessageSelectMode', exitMessageSelectMode);\n\naddActionHandler('openPollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: true,\n };\n});\n\naddActionHandler('closePollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: false,\n };\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('openReactorListModal', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n\n return {\n ...global,\n reactorModal: { chatId, messageId },\n };\n});\n\naddActionHandler('closeReactorListModal', (global) => {\n return {\n ...global,\n reactorModal: undefined,\n };\n});\n\naddActionHandler('openSeenByModal', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n\n return {\n ...global,\n seenByModal: { chatId, messageId },\n };\n});\n\naddActionHandler('closeSeenByModal', (global) => {\n return {\n ...global,\n seenByModal: undefined,\n };\n});\n\naddActionHandler('copySelectedMessages', (global) => {\n if (!global.selectedMessages) {\n return;\n }\n\n const { chatId, messageIds } = global.selectedMessages;\n copyTextForMessages(global, chatId, messageIds);\n});\n\naddActionHandler('copyMessagesByIds', (global, actions, payload: { messageIds?: number[] }) => {\n const { messageIds } = payload;\n const chat = selectCurrentChat(global);\n if (!messageIds || messageIds.length === 0 || !chat) {\n return;\n }\n\n copyTextForMessages(global, chat.id, messageIds);\n});\n\nfunction copyTextForMessages(global: GlobalState, chatId: string, messageIds: number[]) {\n const { threadId } = selectCurrentMessageList(global) || {};\n const lang = langProvider.getTranslation;\n\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages || !threadId) return;\n const messages = messageIds\n .map((id) => chatMessages[id])\n .filter((message) => selectAllowedMessageActions(global, message, threadId).canCopy)\n .sort((message1, message2) => message1.id - message2.id);\n\n const result = messages.reduce((acc, message) => {\n const sender = selectSender(global, message);\n acc.push(`> ${sender ? getSenderTitle(lang, sender) : ''}:`);\n acc.push(`${getMessageSummaryText(lang, message, false, 0, undefined, true)}\\n`);\n\n return acc;\n }, [] as string[]);\n\n copyTextToClipboard(result.join('\\n'));\n}\n","import { addActionHandler } from '../../index';\n\nimport { updateGlobalSearch, updateGlobalSearchContent } from '../../reducers';\n\nconst MAX_RECENTLY_FOUND_IDS = 10;\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('clearRecentlyFoundChats', (global) => {\n return updateGlobalSearch(global, { recentlyFoundChatIds: undefined });\n});\n\naddActionHandler('setGlobalSearchContent', (global, actions, payload) => {\n const { content } = payload!;\n\n return updateGlobalSearchContent(global, content);\n});\n\naddActionHandler('setGlobalSearchChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n return updateGlobalSearch(global, { chatId: id, query: undefined, resultsByType: undefined });\n});\n","import { addActionHandler } from '../../index';\n\naddActionHandler('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\naddActionHandler('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 { addActionHandler } from '../../index';\n\nimport { closeNewContactDialog, updateUserSearch } from '../../reducers';\n\naddActionHandler('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\naddActionHandler('openAddContactDialog', (global, actions, payload) => {\n const { userId } = payload!;\n\n return {\n ...global,\n newContact: { userId },\n };\n});\n\naddActionHandler('openNewContactDialog', (global) => {\n return {\n ...global,\n newContact: {\n isByPhoneNumber: true,\n },\n };\n});\n\naddActionHandler('closeNewContactDialog', (global) => {\n return closeNewContactDialog(global);\n});\n","import { addActionHandler } from '../../index';\n\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\naddActionHandler('toggleChatInfo', (global, action, payload) => {\n return {\n ...global,\n isChatInfoShown: payload !== undefined ? payload : !global.isChatInfoShown,\n };\n});\n\naddActionHandler('setLeftColumnWidth', (global, actions, payload) => {\n const leftColumnWidth = payload;\n\n return {\n ...global,\n leftColumnWidth,\n };\n});\n\naddActionHandler('resetLeftColumnWidth', (global) => {\n return {\n ...global,\n leftColumnWidth: undefined,\n };\n});\n\naddActionHandler('toggleManagement', (global) => {\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\naddActionHandler('requestNextManagementScreen', (global, actions, payload) => {\n const { screen } = payload || {};\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: true,\n nextScreen: screen,\n },\n },\n },\n };\n});\n\naddActionHandler('closeManagement', (global) => {\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\naddActionHandler('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\naddActionHandler('toggleStatistics', (global) => {\n return {\n ...global,\n isStatisticsShown: !global.isStatisticsShown,\n };\n});\n\naddActionHandler('toggleLeftColumn', (global) => {\n return {\n ...global,\n isLeftColumnShown: !global.isLeftColumnShown,\n };\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('dismissDialog', (global) => {\n const newDialogs = [...global.dialogs];\n\n newDialogs.pop();\n\n return {\n ...global,\n dialogs: newDialogs,\n };\n});\n\naddActionHandler('toggleSafeLinkModal', (global, actions, payload) => {\n const { url: safeLinkModalUrl } = payload;\n\n return {\n ...global,\n safeLinkModalUrl,\n };\n});\n\naddActionHandler('openHistoryCalendar', (global, actions, payload) => {\n const { selectedAt } = payload;\n\n return {\n ...global,\n historyCalendarSelectedAt: selectedAt,\n };\n});\n\naddActionHandler('closeHistoryCalendar', (global) => {\n return {\n ...global,\n historyCalendarSelectedAt: undefined,\n };\n});\n","import { addActionHandler } from '../../index';\n\nimport { clearPayment, closeInvoice } from '../../reducers';\n\naddActionHandler('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\naddActionHandler('closePaymentModal', (global) => {\n global = clearPayment(global);\n global = closeInvoice(global);\n return global;\n});\n\naddActionHandler('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 { addActionHandler } from '../../index';\n\naddActionHandler('openMediaViewer', (global, actions, payload) => {\n const {\n chatId, threadId, messageId, avatarOwnerId, profilePhotoIndex, origin, volume, playbackRate, isMuted,\n } = payload;\n\n return {\n ...global,\n mediaViewer: {\n ...global.mediaViewer,\n chatId,\n threadId,\n messageId,\n avatarOwnerId,\n profilePhotoIndex,\n origin,\n volume: volume ?? global.mediaViewer.volume,\n playbackRate: playbackRate || global.mediaViewer.playbackRate,\n isMuted: isMuted || global.mediaViewer.isMuted,\n },\n forwardMessages: {},\n };\n});\n\naddActionHandler('closeMediaViewer', (global) => {\n const { volume, isMuted, playbackRate } = global.mediaViewer;\n return {\n ...global,\n mediaViewer: {\n volume,\n isMuted,\n playbackRate,\n },\n };\n});\n\naddActionHandler('setMediaViewerVolume', (global, actions, payload) => {\n const {\n volume,\n } = payload;\n\n return {\n ...global,\n mediaViewer: {\n ...global.mediaViewer,\n volume,\n },\n };\n});\n\naddActionHandler('setMediaViewerPlaybackRate', (global, actions, payload) => {\n const {\n playbackRate,\n } = payload;\n\n return {\n ...global,\n mediaViewer: {\n ...global.mediaViewer,\n playbackRate,\n },\n };\n});\n\naddActionHandler('setMediaViewerMuted', (global, actions, payload) => {\n const {\n isMuted,\n } = payload;\n\n return {\n ...global,\n mediaViewer: {\n ...global.mediaViewer,\n isMuted,\n },\n };\n});\n","import { addActionHandler, getGlobal, setGlobal } from '../../index';\n\nimport { GlobalActions } from '../../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 {\n MAX_MEDIA_FILES_FOR_ALBUM,\n MESSAGE_LIST_SLICE,\n SERVICE_NOTIFICATIONS_USER_ID,\n} 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\naddActionHandler('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\naddActionHandler('loadMessage', async (global, actions, payload) => {\n const {\n chatId, messageId, replyOriginForId, threadUpdate,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n const message = await loadMessage(chat, messageId, replyOriginForId);\n if (message && threadUpdate) {\n const { lastMessageId, isDeleting } = threadUpdate;\n\n return updateThreadUnreadFromForwardedMessage(\n getGlobal(),\n message,\n chatId,\n lastMessageId,\n isDeleting,\n );\n }\n\n return undefined;\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('toggleMessageWebPage', (global, actions, payload) => {\n const { chatId, threadId, noWebPage } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'noWebPage', noWebPage);\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('deleteHistory', async (global, actions, payload) => {\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\naddActionHandler('reportMessages', async (global, actions, payload) => {\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\naddActionHandler('sendMessageAction', async (global, actions, payload) => {\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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('loadWebPagePreview', (global, actions, payload) => {\n const { text } = payload!;\n void loadWebPagePreview(text);\n});\n\naddActionHandler('clearWebPagePreview', (global) => {\n if (!global.webPagePreview) {\n return undefined;\n }\n\n return {\n ...global,\n webPagePreview: undefined,\n };\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('loadSeenBy', async (global, actions, payload) => {\n const { chatId, messageId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n const result = await callApi('fetchSeenBy', { chat, messageId });\n if (!result) {\n return undefined;\n }\n\n return updateChatMessage(getGlobal(), chatId, messageId, {\n seenByUserIds: result,\n });\n});\n\naddActionHandler('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\naddActionHandler('loadSendAs', async (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n const result = await callApi('fetchSendAs', { chat });\n if (!result) {\n return updateChat(getGlobal(), chatId, {\n sendAsIds: [],\n });\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, { sendAsIds: result.ids });\n return global;\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\naddActionHandler('loadSponsoredMessages', async (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n const result = await callApi('fetchSponsoredMessages', { chat });\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n global = updateSponsoredMessage(global, chatId, result.messages[0]);\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n global = addChats(global, buildCollectionByKey(result.chats, 'id'));\n return global;\n});\n\naddActionHandler('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 { addActionHandler, getGlobal, setGlobal } from '../../index';\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\naddActionHandler('loadStickerSets', (global) => {\n const { hash } = global.stickers.added || {};\n void loadStickerSets(hash);\n});\n\naddActionHandler('loadAddedStickers', async (global, actions) => {\n const { setIds: addedSetIds } = global.stickers.added;\n const cached = global.stickers.setsById;\n if (!addedSetIds || !addedSetIds.length) {\n return;\n }\n\n for (let i = 0; i < addedSetIds.length; i++) {\n const id = addedSetIds[i];\n if (cached[id].stickers) {\n continue; // Already loaded\n }\n actions.loadStickers({ stickerSetId: id });\n\n if (i % ADDED_SETS_THROTTLE_CHUNK === 0 && i > 0) {\n await pause(ADDED_SETS_THROTTLE);\n }\n }\n});\n\naddActionHandler('loadRecentStickers', (global) => {\n const { hash } = global.stickers.recent || {};\n void loadRecentStickers(hash);\n});\n\naddActionHandler('loadFavoriteStickers', (global) => {\n const { hash } = global.stickers.favorite || {};\n void loadFavoriteStickers(hash);\n});\n\naddActionHandler('loadGreetingStickers', async (global) => {\n const { hash } = global.stickers.greeting || {};\n\n const greeting = await callApi('fetchStickersForEmoji', { emoji: '👋⭐️', hash });\n if (!greeting) {\n return undefined;\n }\n\n global = getGlobal();\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n greeting: {\n hash: greeting.hash,\n stickers: greeting.stickers.filter((sticker) => sticker.emoji === '👋'),\n },\n },\n };\n});\n\naddActionHandler('loadFeaturedStickers', (global) => {\n const { hash } = global.stickers.featured || {};\n void loadFeaturedStickers(hash);\n});\n\naddActionHandler('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\naddActionHandler('loadAnimatedEmojis', () => {\n void loadAnimatedEmojis();\n void loadAnimatedEmojiEffects();\n});\n\naddActionHandler('loadSavedGifs', (global) => {\n const { hash } = global.gifs.saved;\n void loadSavedGifs(hash);\n});\n\naddActionHandler('saveGif', async (global, actions, payload) => {\n const { gif, shouldUnsave } = payload!;\n const result = await callApi('saveGif', { gif, shouldUnsave });\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n const gifs = global.gifs.saved.gifs?.filter(({ id }) => id !== gif.id) || [];\n const newGifs = shouldUnsave ? gifs : [gif, ...gifs];\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n saved: {\n ...global.gifs.saved,\n gifs: newGifs,\n },\n },\n };\n});\n\naddActionHandler('faveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void callApi('faveSticker', { sticker });\n }\n});\n\naddActionHandler('unfaveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void unfaveSticker(sticker);\n }\n});\n\naddActionHandler('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\naddActionHandler('loadEmojiKeywords', async (global, actions, payload: { language: LangCode }) => {\n const { language } = payload;\n\n let currentEmojiKeywords = global.emojiKeywords[language];\n if (currentEmojiKeywords?.isLoading) {\n return undefined;\n }\n\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n ...currentEmojiKeywords,\n isLoading: true,\n },\n },\n });\n\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 return {\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n ...currentEmojiKeywords,\n isLoading: false,\n },\n },\n };\n }\n\n return {\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\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\nasync function loadAnimatedEmojiEffects() {\n const stickerSet = await callApi('fetchAnimatedEmojiEffects');\n if (!stickerSet) {\n return;\n }\n\n const { set, stickers } = stickerSet;\n\n setGlobal({\n ...getGlobal(),\n animatedEmojiEffects: { ...set, stickers },\n });\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\naddActionHandler('setStickerSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (query) {\n void searchThrottled(() => {\n searchStickers(query);\n });\n }\n});\n\naddActionHandler('setGifSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (typeof query === 'string') {\n void searchThrottled(() => {\n searchGifs(query);\n });\n }\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('clearStickersForEmoji', (global) => {\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {},\n },\n };\n});\n\naddActionHandler('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 { addActionHandler, getGlobal, setGlobal } from '../../index';\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\naddActionHandler('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\naddActionHandler('setGlobalSearchDate', (global, actions, payload) => {\n const { date } = payload!;\n const maxDate = date ? timestampPlusDay(date) : date;\n\n global = 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(global);\n\n const { chatId } = global.globalSearch;\n const chat = chatId ? selectChat(global, chatId) : undefined;\n searchMessagesGlobal('', 'text', undefined, chat, maxDate, date);\n});\n\naddActionHandler('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 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 addActionHandler, getActions, getGlobal, setGlobal,\n} from '../../index';\n\nimport { ApiChat, 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 selectCurrentMediaSearch,\n selectCurrentMessageList,\n selectChat,\n selectThreadInfo,\n} from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n addChatMessagesById,\n addChats,\n addUsers,\n updateLocalMediaSearchResults,\n updateLocalTextSearchResults,\n} from '../../reducers';\nimport { SharedMediaType } from '../../../types';\n\naddActionHandler('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\naddActionHandler('searchMediaMessagesLocal', (global) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return;\n }\n\n const chat = selectChat(global, chatId);\n const currentSearch = selectCurrentMediaSearch(global);\n\n if (!chat || !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(chat, type, offsetId);\n});\n\naddActionHandler('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 chat: ApiChat,\n threadId: number,\n topMessageId?: number,\n query?: string,\n offsetId?: number,\n) {\n if (!query) {\n return;\n }\n\n const result = await callApi('searchMessagesLocal', {\n chat,\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 chats, users, messages, 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 !== currentSearch.query) {\n return;\n }\n\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = addChatMessagesById(global, chat.id, byId);\n global = updateLocalTextSearchResults(global, chat.id, threadId, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n}\n\nasync function searchSharedMedia(\n chat: ApiChat,\n type: SharedMediaType,\n offsetId?: number,\n isBudgetPreload = false,\n) {\n const result = await callApi('searchMessagesLocal', {\n chat,\n type,\n limit: SHARED_MEDIA_SLICE * 2,\n offsetId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n chats, users, messages, 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 = addChats(global, buildCollectionByKey(chats, 'id'));\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = addChatMessagesById(global, chat.id, byId);\n global = updateLocalMediaSearchResults(global, chat.id, type, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n\n if (!isBudgetPreload) {\n searchSharedMedia(chat, type, nextOffsetId, true);\n }\n}\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 getActions().focusMessage({\n chatId: chat.id,\n messageId,\n });\n}\n","import { addActionHandler, getGlobal, setGlobal } from '../../index';\n\nimport { ManagementProgress } from '../../../types';\nimport { callApi } from '../../../api/gramjs';\nimport { updateChat, updateManagement, updateManagementProgress } from '../../reducers';\nimport { selectChat, selectCurrentMessageList, selectUser } from '../../selectors';\nimport { isChatBasicGroup } from '../../helpers';\n\naddActionHandler('checkPublicLink', async (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return undefined;\n }\n\n // No need to check the username if already in progress\n if (global.management.progress === ManagementProgress.InProgress) {\n return undefined;\n }\n\n const { username } = payload!;\n\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 return global;\n});\n\naddActionHandler('updatePublicLink', async (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n let chat = chatId && selectChat(global, chatId);\n if (!chatId || !chat) {\n return undefined;\n }\n\n const { username } = payload!;\n\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 undefined;\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 return global;\n});\n\naddActionHandler('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\naddActionHandler('setEditingExportedInvite', (global, actions, payload) => {\n const { chatId, invite } = payload;\n\n setGlobal(updateManagement(global, chatId, { editingInvite: invite }));\n});\n\naddActionHandler('setOpenedInviteInfo', (global, actions, payload) => {\n const { chatId, invite } = payload;\n\n const update = invite ? { inviteInfo: { invite } } : { inviteInfo: undefined };\n\n setGlobal(updateManagement(global, chatId, update));\n});\n\naddActionHandler('loadExportedChatInvites', async (global, actions, payload) => {\n const {\n chatId, adminId, isRevoked, limit,\n } = payload!;\n const peer = selectChat(global, chatId);\n const admin = selectUser(global, adminId || global.currentUserId);\n if (!peer || !admin) return undefined;\n\n const result = await callApi('fetchExportedChatInvites', {\n peer, admin, isRevoked, limit,\n });\n if (!result) {\n return undefined;\n }\n\n const update = isRevoked ? { revokedInvites: result } : { invites: result };\n\n return updateManagement(getGlobal(), chatId, update);\n});\n\naddActionHandler('editExportedChatInvite', async (global, actions, payload) => {\n const {\n chatId, link, isRevoked, expireDate, usageLimit, isRequestNeeded, title,\n } = payload!;\n const peer = selectChat(global, chatId);\n if (!peer) return undefined;\n\n const result = await callApi('editExportedChatInvite', {\n peer,\n link,\n isRevoked,\n expireDate,\n usageLimit,\n isRequestNeeded,\n title,\n });\n if (!result) {\n return undefined;\n }\n\n const { oldInvite, newInvite } = result;\n\n global = getGlobal();\n const invites = (global.management.byChatId[chatId].invites || [])\n .filter((current) => current.link !== oldInvite.link);\n const revokedInvites = [...(global.management.byChatId[chatId].revokedInvites || [])];\n\n if (newInvite.isRevoked) {\n revokedInvites.unshift(newInvite);\n } else {\n invites.push(newInvite);\n }\n\n return updateManagement(global, chatId, {\n invites,\n revokedInvites,\n });\n});\n\naddActionHandler('exportChatInvite', async (global, actions, payload) => {\n const {\n chatId, expireDate, usageLimit, isRequestNeeded, title,\n } = payload!;\n const peer = selectChat(global, chatId);\n if (!peer) return undefined;\n\n const result = await callApi('exportChatInvite', {\n peer,\n expireDate,\n usageLimit,\n isRequestNeeded,\n title,\n });\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n const invites = global.management.byChatId[chatId].invites || [];\n return updateManagement(global, chatId, {\n invites: [...invites, result],\n });\n});\n\naddActionHandler('deleteExportedChatInvite', async (global, actions, payload) => {\n const {\n chatId, link,\n } = payload!;\n const peer = selectChat(global, chatId);\n if (!peer) return undefined;\n\n const result = await callApi('deleteExportedChatInvite', {\n peer,\n link,\n });\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n const managementState = global.management.byChatId[chatId];\n return updateManagement(global, chatId, {\n invites: managementState?.invites?.filter((invite) => invite.link !== link),\n revokedInvites: managementState?.revokedInvites?.filter((invite) => invite.link !== link),\n });\n});\n\naddActionHandler('deleteRevokedExportedChatInvites', async (global, actions, payload) => {\n const {\n chatId, adminId,\n } = payload!;\n const peer = selectChat(global, chatId);\n const admin = selectUser(global, adminId || global.currentUserId);\n if (!peer || !admin) return undefined;\n\n const result = await callApi('deleteRevokedExportedChatInvites', {\n peer,\n admin,\n });\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n return updateManagement(global, chatId, {\n revokedInvites: [],\n });\n});\n\naddActionHandler('loadChatInviteImporters', async (global, actions, payload) => {\n const {\n chatId, link, offsetDate, offsetUserId, limit,\n } = payload!;\n const peer = selectChat(global, chatId);\n const offsetUser = selectUser(global, offsetUserId);\n if (!peer || (offsetUserId && !offsetUser)) return undefined;\n\n const result = await callApi('fetchChatInviteImporters', {\n peer,\n link,\n offsetDate,\n offsetUser,\n limit,\n });\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n const currentInviteInfo = global.management.byChatId[chatId]?.inviteInfo;\n if (!currentInviteInfo?.invite || currentInviteInfo.invite.link !== link) {\n return undefined;\n }\n\n return updateManagement(global, chatId, {\n inviteInfo: {\n ...currentInviteInfo,\n importers: result,\n },\n });\n});\n\naddActionHandler('loadChatInviteRequesters', async (global, actions, payload) => {\n const {\n chatId, link, offsetDate, offsetUserId, limit,\n } = payload!;\n const peer = selectChat(global, chatId);\n const offsetUser = selectUser(global, offsetUserId);\n if (!peer || (offsetUserId && !offsetUser)) return undefined;\n\n const result = await callApi('fetchChatInviteImporters', {\n peer,\n link,\n offsetDate,\n offsetUser,\n limit,\n isRequested: true,\n });\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n const currentInviteInfo = global.management.byChatId[chatId]?.inviteInfo;\n if (!currentInviteInfo?.invite || currentInviteInfo.invite.link !== link) {\n return undefined;\n }\n\n return updateManagement(global, chatId, {\n inviteInfo: {\n ...currentInviteInfo,\n requesters: result,\n },\n });\n});\n\naddActionHandler('loadChatJoinRequests', async (global, actions, payload) => {\n const {\n chatId, offsetDate, offsetUserId, limit,\n } = payload!;\n const peer = selectChat(global, chatId);\n const offsetUser = selectUser(global, offsetUserId);\n if (!peer || (offsetUserId && !offsetUser)) return undefined;\n\n const result = await callApi('fetchChatInviteImporters', {\n peer,\n offsetDate,\n offsetUser,\n limit,\n isRequested: true,\n });\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n return updateChat(global, chatId, { joinRequests: result });\n});\n\naddActionHandler('hideChatJoinRequest', async (global, actions, payload) => {\n const {\n chatId, userId, isApproved,\n } = payload!;\n const peer = selectChat(global, chatId);\n const user = selectUser(global, userId);\n if (!peer || !user) return undefined;\n\n const result = await callApi('hideChatJoinRequest', {\n peer,\n user,\n isApproved,\n });\n if (!result) return undefined;\n\n global = getGlobal();\n const targetChat = selectChat(global, chatId);\n if (!targetChat) return undefined;\n\n return updateChat(global, chatId, {\n joinRequests: targetChat.joinRequests?.filter((importer) => importer.userId !== userId),\n });\n});\n\naddActionHandler('hideAllChatJoinRequests', async (global, actions, payload) => {\n const {\n chatId, isApproved, link,\n } = payload!;\n const peer = selectChat(global, chatId);\n if (!peer) return undefined;\n\n const result = await callApi('hideAllChatJoinRequests', {\n peer,\n isApproved,\n link,\n });\n if (!result) return undefined;\n\n global = getGlobal();\n const targetChat = selectChat(global, chatId);\n if (!targetChat) return undefined;\n\n return updateChat(global, chatId, {\n joinRequests: [],\n fullInfo: {\n ...targetChat.fullInfo,\n recentRequesterIds: [],\n requestsPending: 0,\n },\n });\n});\n\naddActionHandler('hideChatReportPanel', async (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) return undefined;\n\n const result = await callApi('hideChatReportPanel', chat);\n if (!result) return undefined;\n\n return updateChat(getGlobal(), chatId, {\n settings: undefined,\n });\n});\n","import {\n addActionHandler, getGlobal, setGlobal, getActions,\n} from '../../index';\n\nimport {\n ApiChat, ApiMessage, MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { Thread } from '../../types';\n\nimport {\n DEBUG, MESSAGE_LIST_SLICE, SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n updateUsers,\n updateChats,\n updateThreadInfos,\n updateListedIds,\n safeReplaceViewportIds,\n addChatMessagesById,\n updateThread,\n} from '../../reducers';\nimport {\n selectCurrentMessageList,\n selectDraft,\n selectChatMessage,\n selectThreadInfo,\n selectEditingId,\n selectEditingDraft,\n} from '../../selectors';\nimport { init as initFolderManager } from '../../../util/folderManager';\n\nconst RELEASE_STATUS_TIMEOUT = 15000; // 10 sec;\n\nlet releaseStatusTimeout: number | undefined;\n\naddActionHandler('sync', () => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START SYNC');\n }\n\n if (releaseStatusTimeout) {\n clearTimeout(releaseStatusTimeout);\n }\n\n setGlobal({ ...getGlobal(), isSyncing: true });\n\n // Workaround for `isSyncing = true` sometimes getting stuck for some reason\n releaseStatusTimeout = window.setTimeout(() => {\n setGlobal({ ...getGlobal(), isSyncing: false });\n releaseStatusTimeout = undefined;\n }, RELEASE_STATUS_TIMEOUT);\n\n const { loadAllChats, preloadTopChatMessages } = getActions();\n\n loadAllChats({\n listType: 'active',\n shouldReplace: true,\n onReplace: async () => {\n await loadAndReplaceMessages();\n\n setGlobal({\n ...getGlobal(),\n lastSyncTime: Date.now(),\n isSyncing: false,\n });\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH SYNC');\n }\n\n initFolderManager();\n loadAllChats({ listType: 'archived', shouldReplace: true });\n void callApi('fetchCurrentUser');\n preloadTopChatMessages();\n },\n });\n});\n\nasync function loadAndReplaceMessages() {\n let areMessagesLoaded = false;\n\n let global = getGlobal();\n\n // Memoize drafts\n const draftChatIds = Object.keys(global.messages.byChatId);\n const draftsByChatId = draftChatIds.reduce>>((acc, chatId) => {\n acc[chatId] = {};\n acc[chatId].draft = selectDraft(global, chatId, MAIN_THREAD_ID);\n acc[chatId].editingId = selectEditingId(global, chatId, MAIN_THREAD_ID);\n acc[chatId].editingDraft = selectEditingDraft(global, chatId, MAIN_THREAD_ID);\n\n return acc;\n }, {});\n\n const { chatId: currentChatId, threadId: currentThreadId } = selectCurrentMessageList(global) || {};\n const currentChat = currentChatId ? global.chats.byId[currentChatId] : undefined;\n if (currentChatId && currentChat) {\n const result = await loadTopMessages(currentChat);\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 = updateUsers(global, buildCollectionByKey(result.users, 'id'));\n global = updateThreadInfos(global, currentChatId, result.threadInfos);\n\n areMessagesLoaded = true;\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 = updateThread(global, chatId, MAIN_THREAD_ID, draftsByChatId[chatId]);\n });\n\n setGlobal(global);\n\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n if (audioChatId && audioMessageId && !selectChatMessage(global, audioChatId, audioMessageId)) {\n getActions().closeAudioPlayer();\n }\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 addActionHandler, getActions, getGlobal, setGlobal,\n} from '../../index';\n\nimport { ApiUser } from '../../../api/types';\nimport { ManagementProgress } from '../../../types';\n\nimport { debounce, throttle } from '../../../util/schedulers';\nimport { buildCollectionByKey, unique } from '../../../util/iteratees';\nimport { isUserBot, isUserId } from '../../helpers';\nimport { callApi } from '../../../api/gramjs';\nimport { selectChat, selectCurrentMessageList, selectUser } from '../../selectors';\nimport {\n addChats, addUsers, closeNewContactDialog, replaceUserStatuses, updateChat, updateManagementProgress, updateUser,\n updateUsers, updateUserSearch, updateUserSearchFetchingStatus,\n} from '../../reducers';\nimport { getServerTime } from '../../../util/serverTime';\nimport * as langProvider from '../../../util/langProvider';\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\naddActionHandler('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\naddActionHandler('loadUser', async (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return undefined;\n }\n\n const result = await callApi('fetchUsers', { users: [user] });\n if (!result) {\n return undefined;\n }\n\n const { users, userStatusesById } = result;\n\n global = getGlobal();\n\n global = updateUsers(global, buildCollectionByKey(users, 'id'));\n global = replaceUserStatuses(global, {\n ...global.users.statusesById,\n ...userStatusesById,\n });\n\n return global;\n});\n\naddActionHandler('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\naddActionHandler('loadContactList', () => {\n void loadContactList();\n});\n\naddActionHandler('loadCurrentUser', () => {\n void callApi('fetchCurrentUser');\n});\n\naddActionHandler('loadCommonChats', async (global) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const user = chatId ? selectUser(global, chatId) : undefined;\n if (!user || isUserBot(user) || user.commonChats?.isFullyLoaded) {\n return undefined;\n }\n\n const maxId = user.commonChats?.maxId;\n const result = await callApi('fetchCommonChats', user.id, user.accessHash!, maxId);\n if (!result) {\n return undefined;\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\n return global;\n});\n\naddActionHandler('updateContact', (global, actions, payload) => {\n const {\n userId, isMuted = false, firstName, lastName, shouldSharePhoneNumber,\n } = payload;\n\n void updateContact(userId, isMuted, firstName, lastName, shouldSharePhoneNumber);\n});\n\naddActionHandler('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 shouldSharePhoneNumber?: boolean,\n) {\n let global = getGlobal();\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n getActions().updateChatMutedState({ chatId: userId, isMuted });\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.InProgress));\n\n let result;\n if (!user.isContact && user.phoneNumber) {\n result = await callApi('importContact', { phone: user.phoneNumber, firstName, lastName });\n } else {\n const { id, accessHash } = user;\n result = await callApi('updateContact', {\n id,\n accessHash,\n phoneNumber: '',\n firstName,\n lastName,\n shouldSharePhoneNumber,\n });\n }\n\n global = getGlobal();\n if (result) {\n setGlobal(updateUser(\n global,\n user.id,\n {\n firstName,\n lastName,\n },\n ));\n }\n\n global = updateManagementProgress(global, ManagementProgress.Complete);\n global = closeNewContactDialog(global);\n setGlobal(global);\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\naddActionHandler('loadProfilePhotos', async (global, actions, payload) => {\n const { profileId } = payload!;\n const isPrivate = isUserId(profileId);\n\n const user = isPrivate ? selectUser(global, profileId) : undefined;\n const chat = !isPrivate ? selectChat(global, profileId) : undefined;\n if (!user && !chat) {\n return undefined;\n }\n\n const result = await callApi('fetchProfilePhotos', user, chat);\n if (!result || !result.photos) {\n return undefined;\n }\n\n global = getGlobal();\n\n if (isPrivate) {\n global = updateUser(global, profileId, { photos: result.photos });\n } else {\n global = addUsers(global, buildCollectionByKey(result.users!, 'id'));\n global = updateChat(global, profileId, { photos: result.photos });\n }\n\n return global;\n});\n\naddActionHandler('setUserSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (!query) return;\n\n void runThrottledForSearch(() => {\n searchUsers(query);\n });\n});\n\naddActionHandler('importContact', async (global, actions, payload) => {\n const { phoneNumber: phone, firstName, lastName } = payload!;\n\n const result = await callApi('importContact', { phone, firstName, lastName });\n\n if (result) {\n actions.openChat({ id: result });\n\n return closeNewContactDialog(getGlobal());\n }\n\n actions.showNotification({\n message: langProvider.getTranslation('Contacts.PhoneNumber.NotRegistred'),\n });\n\n return undefined;\n});\n\naddActionHandler('reportSpam', (global, actions, payload) => {\n const { chatId } = payload!;\n const userOrChat = isUserId(chatId) ? selectUser(global, chatId) : selectChat(global, chatId);\n if (!userOrChat) {\n return;\n }\n\n void callApi('reportSpam', userOrChat);\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 '../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 addActionHandler, getActions, getGlobal, setGlobal,\n} from '../../index';\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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('restartBot', async (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 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\naddActionHandler('loadTopInlineBots', async (global) => {\n const { lastRequestedAt } = global.topInlineBots;\n if (lastRequestedAt && getServerTime(global.serverTimeOffset) - lastRequestedAt < TOP_PEERS_REQUEST_COOLDOWN) {\n return undefined;\n }\n\n const result = await callApi('fetchTopInlineBots');\n if (!result) {\n return undefined;\n }\n\n const { ids, users } = result;\n\n global = getGlobal();\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = {\n ...global,\n topInlineBots: {\n ...global.topInlineBots,\n userIds: ids,\n lastRequestedAt: getServerTime(global.serverTimeOffset),\n },\n };\n return global;\n});\n\naddActionHandler('queryInlineBot', async (global, actions, payload) => {\n const {\n chatId, username, query, offset,\n } = payload;\n\n let inlineBotData = global.inlineBots.byUsername[username];\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\naddActionHandler('sendInlineBotResult', (global, actions, payload) => {\n const {\n id, queryId, isSilent, scheduledAt,\n } = payload;\n const currentMessageList = selectCurrentMessageList(global);\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 isSilent,\n scheduleDate: scheduledAt,\n });\n});\n\naddActionHandler('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\naddActionHandler('startBot', async (global, actions, payload) => {\n const { botId, param } = payload;\n\n const bot = selectUser(global, botId);\n if (!bot) {\n return;\n }\n\n await callApi('startBot', {\n bot,\n startParam: param,\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 } = getActions();\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 { addActionHandler, getGlobal, setGlobal } from '../../index';\n\nimport { callApi } from '../../../api/gramjs';\nimport { replaceSettings, updateTwoFaSettings } from '../../reducers';\n\naddActionHandler('loadPasswordInfo', async (global) => {\n const result = await callApi('getPasswordInfo');\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n global = replaceSettings(global, { hasPassword: result.hasPassword });\n global = updateTwoFaSettings(global, { hint: result.hint });\n return global;\n});\n\naddActionHandler('checkPassword', async (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n const isSuccess = await callApi('checkPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n});\n\naddActionHandler('clearPassword', async (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n const isSuccess = await callApi('clearPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n});\n\naddActionHandler('updatePassword', async (global, actions, payload) => {\n const {\n currentPassword, password, hint, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\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\naddActionHandler('updateRecoveryEmail', async (global, actions, payload) => {\n const {\n currentPassword, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\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\naddActionHandler('provideTwoFaEmailCode', (global, actions, payload) => {\n const { code } = payload;\n\n void callApi('provideRecoveryEmailCode', code);\n});\n\naddActionHandler('clearTwoFaError', (global) => {\n return updateTwoFaSettings(global, { error: undefined });\n});\n","import { addActionHandler, getGlobal, setGlobal } from '../../index';\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 selectProviderPublicToken,\n selectSmartGlocalCredentials,\n} from '../../selectors';\nimport { callApi } from '../../../api/gramjs';\nimport { getStripeError } from '../../helpers';\nimport { buildQueryString } from '../../../util/requestQuery';\nimport { DEBUG_PAYMENT_SMART_GLOCAL } from '../../../config';\n\nimport {\n updateShippingOptions,\n setPaymentStep,\n setRequestInfoId,\n setPaymentForm,\n setStripeCardInfo,\n setInvoiceMessageInfo,\n setReceipt,\n clearPayment,\n closeInvoice,\n setSmartGlocalCardInfo,\n} from '../../reducers';\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('clearPaymentError', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n error: undefined,\n },\n });\n});\n\naddActionHandler('clearReceipt', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n });\n});\n\naddActionHandler('sendCredentialsInfo', (global, actions, payload) => {\n const { nativeProvider } = global.payment;\n const { credentials } = payload;\n const { data } = credentials;\n\n if (nativeProvider === 'stripe') {\n const publishableKey = selectProviderPublishableKey(global);\n if (!publishableKey) {\n return;\n }\n void sendStripeCredentials(data, publishableKey);\n } else if (nativeProvider === 'smartglocal') {\n const publicToken = selectProviderPublicToken(global);\n if (!publicToken) {\n return;\n }\n void sendSmartGlocalCredentials(data, publicToken);\n }\n});\n\naddActionHandler('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 { nativeProvider } = global.payment;\n const publishableKey = nativeProvider === 'stripe'\n ? selectProviderPublishableKey(global) : selectProviderPublicToken(global);\n if (!chat || !messageId || !publishableKey || !formId || !nativeProvider) {\n return;\n }\n\n void sendPaymentForm(chat, messageId, nativeProvider, formId, {\n save: saveCredentials,\n data: nativeProvider === 'stripe' ? selectStripeCredentials(global) : selectSmartGlocalCredentials(global),\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 sendSmartGlocalCredentials(\n data: {\n cardNumber: string;\n cardholder?: string;\n expiryMonth: string;\n expiryYear: string;\n cvv: string;\n },\n publicToken: string,\n) {\n const params = {\n card: {\n number: data.cardNumber.replace(/[^\\d]+/g, ''),\n expiration_month: data.expiryMonth,\n expiration_year: data.expiryYear,\n security_code: data.cvv.replace(/[^\\d]+/g, ''),\n },\n };\n const url = DEBUG_PAYMENT_SMART_GLOCAL\n ? 'https://tgb-playground.smart-glocal.com/cds/v1/tokenize/card'\n : 'https://tgb.smart-glocal.com/cds/v1/tokenize/card';\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'X-PUBLIC-TOKEN': publicToken,\n },\n body: JSON.stringify(params),\n });\n const result = await response.json();\n\n if (result.status !== 'ok') {\n // TODO после получения документации сделать аналог getStripeError(result.error);\n const error = { description: 'payment 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\n let global = setSmartGlocalCardInfo(getGlobal(), {\n type: 'card',\n token: result.data.token,\n });\n global = setPaymentStep(global, PaymentStep.Checkout);\n setGlobal(global);\n}\n\nasync function sendPaymentForm(\n chat: ApiChat,\n messageId: number,\n nativeProvider: string,\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\n if (result === true) {\n const global = clearPayment(getGlobal());\n setGlobal(closeInvoice(global));\n }\n}\n\naddActionHandler('setPaymentStep', (global, actions, payload = {}) => {\n return setPaymentStep(global, payload.step || PaymentStep.ShippingInfo);\n});\n\naddActionHandler('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 {\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;\nexport const SIDE_COLUMN_MAX_WIDTH = 26.5 * REM;\nexport const 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 { updateChatMessage } from './messages';\nimport { GlobalState } from '../types';\nimport { selectChatMessage } from '../selectors';\nimport { MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN, MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN } from '../../config';\nimport {\n MIN_LEFT_COLUMN_WIDTH,\n SIDE_COLUMN_MAX_WIDTH,\n} from '../../components/middle/helpers/calculateMiddleFooterTransforms';\nimport { IS_SINGLE_COLUMN_LAYOUT } from '../../util/environment';\nimport windowSize from '../../util/windowSize';\n\nfunction getLeftColumnWidth(windowWidth: number) {\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN) {\n return Math.min(\n Math.max(windowWidth * 0.25, MIN_LEFT_COLUMN_WIDTH),\n windowWidth * 0.33,\n );\n }\n\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN) {\n return Math.min(\n Math.max(windowWidth * 0.33, MIN_LEFT_COLUMN_WIDTH),\n windowWidth * 0.4,\n );\n }\n\n return SIDE_COLUMN_MAX_WIDTH;\n}\n\nexport function subtractXForEmojiInteraction(global: GlobalState, x: number) {\n return x - ((global.isLeftColumnShown && !IS_SINGLE_COLUMN_LAYOUT)\n ? global.leftColumnWidth || getLeftColumnWidth(windowSize.get().width)\n : 0);\n}\n\nexport function addMessageReaction(global: GlobalState, chatId: string, messageId: number, reaction: string) {\n const { reactions } = selectChatMessage(global, chatId, messageId) || {};\n\n if (!reactions) {\n return global;\n }\n\n // Update UI without waiting for server response\n let results = reactions.results.map((l) => (l.reaction === reaction\n ? {\n ...l,\n count: l.isChosen ? l.count : l.count + 1,\n isChosen: true,\n } : (l.isChosen ? {\n ...l,\n isChosen: false,\n count: l.count - 1,\n } : l)))\n .filter((l) => l.count > 0);\n\n let { recentReactions } = reactions;\n\n if (reaction && !results.some((l) => l.reaction === reaction)) {\n const { currentUserId } = global;\n\n results = [...results, {\n reaction,\n isChosen: true,\n count: 1,\n }];\n\n if (reactions.canSeeList) {\n recentReactions = [...(recentReactions || []), {\n userId: currentUserId!,\n reaction,\n }];\n }\n }\n\n return updateChatMessage(global, chatId, messageId, {\n reactions: {\n ...reactions,\n results,\n recentReactions,\n },\n });\n}\n","import { addActionHandler, getGlobal } from '../../index';\nimport { callApi } from '../../../api/gramjs';\nimport * as mediaLoader from '../../../util/mediaLoader';\nimport { ApiAppConfig, ApiMediaFormat } from '../../../api/types';\nimport {\n selectChat,\n selectChatMessage,\n selectDefaultReaction,\n selectLocalAnimatedEmojiEffectByName,\n selectMessageIdsByGroupId,\n} from '../../selectors';\nimport { addMessageReaction, subtractXForEmojiInteraction } from '../../reducers/reactions';\nimport { addUsers, updateChatMessage } from '../../reducers';\nimport { buildCollectionByKey, omit } from '../../../util/iteratees';\nimport { ANIMATION_LEVEL_MAX } from '../../../config';\nimport { isMessageLocal } from '../../helpers';\n\nconst INTERACTION_RANDOM_OFFSET = 40;\n\nlet interactionLocalId = 0;\n\naddActionHandler('loadAvailableReactions', async () => {\n const result = await callApi('getAvailableReactions');\n if (!result) {\n return undefined;\n }\n\n // Preload animations\n result.forEach((availableReaction) => {\n if (availableReaction.aroundAnimation) {\n mediaLoader.fetch(`sticker${availableReaction.aroundAnimation.id}`, ApiMediaFormat.Lottie);\n }\n if (availableReaction.centerIcon) {\n mediaLoader.fetch(`sticker${availableReaction.centerIcon.id}`, ApiMediaFormat.Lottie);\n }\n });\n\n return {\n ...getGlobal(),\n availableReactions: result,\n };\n});\n\naddActionHandler('interactWithAnimatedEmoji', (global, actions, payload) => {\n const {\n emoji, x, y, localEffect, startSize, isReversed,\n } = payload!;\n\n const activeEmojiInteraction = {\n id: interactionLocalId++,\n animatedEffect: emoji || localEffect,\n x: subtractXForEmojiInteraction(global, x) + Math.random()\n * INTERACTION_RANDOM_OFFSET - INTERACTION_RANDOM_OFFSET / 2,\n y: y + Math.random() * INTERACTION_RANDOM_OFFSET - INTERACTION_RANDOM_OFFSET / 2,\n startSize,\n isReversed,\n };\n\n return {\n ...global,\n activeEmojiInteractions: [...(global.activeEmojiInteractions || []), activeEmojiInteraction],\n };\n});\n\naddActionHandler('sendEmojiInteraction', (global, actions, payload) => {\n const {\n messageId, chatId, emoji, interactions, localEffect,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n\n if (!chat || (!emoji && !localEffect) || chatId === global.currentUserId) {\n return;\n }\n\n void callApi('sendEmojiInteraction', {\n chat,\n messageId,\n emoticon: emoji || selectLocalAnimatedEmojiEffectByName(localEffect),\n timestamps: interactions,\n });\n});\n\naddActionHandler('sendDefaultReaction', (global, actions, payload) => {\n const {\n chatId, messageId, x, y,\n } = payload;\n const reaction = selectDefaultReaction(global, chatId);\n const message = selectChatMessage(global, chatId, messageId);\n\n if (!reaction || !message || isMessageLocal(message)) return;\n\n actions.sendReaction({\n chatId,\n messageId,\n reaction,\n x,\n y,\n });\n});\n\naddActionHandler('sendReaction', (global, actions, payload) => {\n const {\n chatId,\n }: { chatId: string } = payload;\n let { messageId } = payload;\n\n let { reaction } = payload;\n\n const chat = selectChat(global, chatId);\n let message = selectChatMessage(global, chatId, messageId);\n\n if (!chat || !message) {\n return undefined;\n }\n\n const isInDocumentGroup = Boolean(message.groupedId) && !message.isInAlbum;\n const documentGroupFirstMessageId = isInDocumentGroup\n ? selectMessageIdsByGroupId(global, chatId, message.groupedId!)![0]\n : undefined;\n message = isInDocumentGroup\n ? selectChatMessage(global, chatId, documentGroupFirstMessageId!) || message\n : message;\n messageId = message?.id || messageId;\n\n if (message.reactions?.results?.some((l) => l.reaction === reaction && l.isChosen)) {\n reaction = undefined;\n }\n\n void callApi('sendReaction', { chat, messageId, reaction });\n\n const { animationLevel } = global.settings.byKey;\n\n if (animationLevel === ANIMATION_LEVEL_MAX) {\n global = {\n ...global,\n activeReactions: {\n ...(reaction ? global.activeReactions : omit(global.activeReactions, [messageId])),\n ...(reaction && {\n [messageId]: {\n reaction,\n messageId,\n },\n }),\n },\n };\n }\n\n return addMessageReaction(global, chatId, messageId, reaction);\n});\n\naddActionHandler('openChat', (global) => {\n return {\n ...global,\n activeReactions: {},\n };\n});\n\naddActionHandler('startActiveReaction', (global, actions, payload) => {\n const { messageId, reaction } = payload;\n const { animationLevel } = global.settings.byKey;\n\n if (animationLevel !== ANIMATION_LEVEL_MAX) return global;\n\n if (global.activeReactions[messageId]?.reaction === reaction) {\n return global;\n }\n\n return {\n ...global,\n activeReactions: {\n ...(reaction ? global.activeReactions : omit(global.activeReactions, [messageId])),\n ...(reaction && {\n [messageId]: {\n reaction,\n messageId,\n },\n }),\n },\n };\n});\n\naddActionHandler('stopActiveReaction', (global, actions, payload) => {\n const { messageId, reaction } = payload;\n\n if (global.activeReactions[messageId]?.reaction !== reaction) {\n return global;\n }\n\n return {\n ...global,\n activeReactions: omit(global.activeReactions, [messageId]),\n };\n});\n\naddActionHandler('setDefaultReaction', async (global, actions, payload) => {\n const { reaction } = payload;\n\n const result = await callApi('setDefaultReaction', { reaction });\n if (!result) {\n return undefined;\n }\n\n return {\n ...getGlobal(),\n appConfig: {\n ...global.appConfig,\n defaultReaction: reaction,\n } as ApiAppConfig,\n };\n});\n\naddActionHandler('stopActiveEmojiInteraction', (global, actions, payload) => {\n const { id } = payload;\n\n return {\n ...global,\n activeEmojiInteractions: global.activeEmojiInteractions?.filter((l) => l.id !== id),\n };\n});\n\naddActionHandler('loadReactors', async (global, actions, payload) => {\n const { chatId, messageId, reaction } = payload;\n const chat = selectChat(global, chatId);\n const message = selectChatMessage(global, chatId, messageId);\n if (!chat || !message) {\n return undefined;\n }\n\n const offset = message.reactors?.nextOffset;\n const result = await callApi('fetchMessageReactionsList', {\n reaction,\n chat,\n messageId,\n offset,\n });\n\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n\n if (result.users?.length) {\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n }\n\n const { nextOffset, count, reactions } = result;\n\n return updateChatMessage(global, chatId, messageId, {\n reactors: {\n nextOffset,\n count,\n reactions: [\n ...(message.reactors?.reactions || []),\n ...reactions,\n ],\n },\n });\n});\n\naddActionHandler('loadMessageReactions', (global, actions, payload) => {\n const { ids, chatId } = payload;\n\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n callApi('fetchMessageReactions', { ids, chat });\n});\n\naddActionHandler('sendWatchingEmojiInteraction', (global, actions, payload) => {\n const {\n chatId, emoticon, x, y, startSize, isReversed, id,\n } = payload;\n\n const chat = selectChat(global, chatId);\n\n if (!chat || !global.activeEmojiInteractions?.some((l) => l.id === id) || chatId === global.currentUserId) {\n return undefined;\n }\n\n callApi('sendWatchingEmojiInteraction', { chat, emoticon });\n\n return {\n ...global,\n activeEmojiInteractions: global.activeEmojiInteractions.map((activeEmojiInteraction) => {\n if (activeEmojiInteraction.id === id) {\n return {\n ...activeEmojiInteraction,\n x: subtractXForEmojiInteraction(global, x),\n y,\n startSize,\n isReversed,\n };\n }\n return activeEmojiInteraction;\n }),\n };\n});\n","import { addActionHandler, getGlobal } from '../../index';\n\nimport { ApiChannelStatistics } from '../../../api/types';\nimport { callApi } from '../../../api/gramjs';\nimport { updateStatistics, updateStatisticsGraph } from '../../reducers';\nimport { selectChatMessages, selectChat } from '../../selectors';\n\naddActionHandler('loadStatistics', async (global, actions, payload) => {\n const { chatId, isGroup } = payload;\n const chat = selectChat(global, chatId);\n if (!chat?.fullInfo) {\n return undefined;\n }\n\n const result = await callApi(isGroup ? 'fetchGroupStatistics' : 'fetchChannelStatistics', { chat });\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n\n if ((result as ApiChannelStatistics).recentTopMessages?.length) {\n const messages = selectChatMessages(global, chatId);\n\n (result as ApiChannelStatistics).recentTopMessages = (result as ApiChannelStatistics).recentTopMessages\n .map((message) => ({ ...message, ...messages[message.msgId] }));\n }\n\n global = updateStatistics(global, chatId, result);\n\n return global;\n});\n\naddActionHandler('loadStatisticsAsyncGraph', async (global, actions, payload) => {\n const {\n chatId, token, name, isPercentage,\n } = payload;\n const chat = selectChat(global, chatId);\n if (!chat?.fullInfo) {\n return undefined;\n }\n\n const dcId = chat.fullInfo!.statisticsDcId;\n const result = await callApi('fetchStatisticsAsyncGraph', { token, dcId, isPercentage });\n\n if (!result) {\n return undefined;\n }\n\n return updateStatisticsGraph(getGlobal(), chatId, name, result);\n});\n","export function areDeepEqual(value1: T, value2: T): boolean {\n const type1 = typeof value1;\n const type2 = typeof value2;\n if (type1 !== type2) {\n return false;\n }\n\n if (type1 !== 'object') {\n return value1 === value2;\n }\n\n const isArray1 = Array.isArray(value1);\n const isArray2 = Array.isArray(value2);\n\n if (isArray1 !== isArray2) {\n return false;\n }\n\n if (isArray1) {\n const array1 = value1 as any[];\n const array2 = value2 as any[];\n\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((member1, i) => areDeepEqual(member1, array2[i]));\n }\n\n const object1 = value1 as AnyLiteral;\n const object2 = value2 as AnyLiteral;\n const keys1 = Object.keys(object1);\n\n return keys1.every((key1) => areDeepEqual(object1[key1], object2[key1]));\n}\n","import { addActionHandler, getGlobal, setGlobal } from '../../index';\n\nimport { MAIN_THREAD_ID } from '../../../api/types';\n\nimport { ARCHIVED_FOLDER_ID, MAX_ACTIVE_PINNED_CHATS } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { closeMessageNotifications, notifyAboutMessage } from '../../../util/notifications';\nimport { getMessageRecentReaction } from '../../helpers';\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} from '../../selectors';\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\naddActionHandler('apiUpdate', (global, actions, update) => {\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 setGlobal(updateChat(global, update.id, update.chat, update.newProfilePhoto));\n\n if (update.chat.id) {\n closeMessageNotifications({\n chatId: update.chat.id,\n lastReadInboxMessageId: update.chat.lastReadInboxMessageId,\n });\n }\n\n return undefined;\n }\n\n case 'updateChatJoin': {\n const listType = selectChatListType(global, update.id);\n if (!listType) {\n return undefined;\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\n return undefined;\n }\n\n case 'updateChatLeave': {\n return leaveChat(global, update.id);\n }\n\n case 'updateChatInbox': {\n return updateChat(global, update.id, update.chat);\n }\n\n case 'updateChatTypingStatus': {\n const { id, typingStatus } = update;\n setGlobal(updateChat(global, id, { typingStatus }));\n\n setTimeout(() => {\n global = getGlobal();\n const chat = selectChat(global, id);\n if (chat && typingStatus && chat.typingStatus && chat.typingStatus.timestamp === typingStatus.timestamp) {\n setGlobal(updateChat(global, id, { typingStatus: undefined }));\n }\n }, TYPING_STATUS_CLEAR_DELAY);\n\n return undefined;\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 undefined;\n }\n\n const chat = selectChat(global, update.chatId);\n if (!chat) {\n return undefined;\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 notifyAboutMessage({\n chat,\n message,\n });\n\n return undefined;\n }\n\n case 'updateMessage': {\n const { message } = update;\n const chat = selectChat(global, update.chatId);\n if (!chat) {\n return undefined;\n }\n\n if (getMessageRecentReaction(message)) {\n notifyAboutMessage({\n chat,\n message,\n });\n }\n\n return undefined;\n }\n\n case 'updateCommonBoxMessages':\n case 'updateChannelMessages': {\n const { ids, messageUpdate } = update;\n if (messageUpdate.hasUnreadMention !== false) {\n return undefined;\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 return global;\n }\n\n case 'updateChatFullInfo': {\n const { fullInfo } = update;\n const targetChat = global.chats.byId[update.id];\n if (!targetChat) {\n return undefined;\n }\n\n return updateChat(global, update.id, {\n fullInfo: {\n ...targetChat.fullInfo,\n ...fullInfo,\n },\n });\n }\n\n case 'updatePinnedChatIds': {\n const { ids, folderId } = update;\n const listType = folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n\n return {\n ...global,\n chats: {\n ...global.chats,\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [listType]: ids.length ? ids : undefined,\n },\n },\n };\n }\n\n case 'updateChatPinned': {\n const { id, isPinned } = update;\n const listType = selectChatListType(global, id);\n if (!listType) {\n return undefined;\n }\n\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 return {\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 case 'updateChatListType': {\n const { id, folderId } = update;\n\n return updateChatListType(global, id, folderId);\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 return {\n ...global,\n chatFolders: {\n ...global.chatFolders,\n byId: newChatFoldersById,\n orderedIds: newOrderedIds,\n },\n };\n }\n\n case 'updateChatFoldersOrder': {\n const { orderedIds } = update;\n\n return {\n ...global,\n chatFolders: {\n ...global.chatFolders,\n orderedIds,\n },\n };\n }\n\n case 'updateRecommendedChatFolders': {\n const { folders } = update;\n\n return {\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: folders,\n },\n };\n }\n\n case 'updateChatMembers': {\n const targetChat = global.chats.byId[update.id];\n const { replacedMembers, addedMember, deletedMemberId } = update;\n if (!targetChat) {\n return undefined;\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 return updateChat(global, update.id, {\n membersCount: members.length,\n fullInfo: {\n ...targetChat.fullInfo,\n members,\n adminMembers,\n },\n });\n }\n\n return undefined;\n }\n\n case 'deleteProfilePhotos': {\n const { chatId, ids } = update;\n const chat = global.chats.byId[chatId];\n\n if (chat?.photos) {\n return updateChat(global, chatId, {\n photos: chat.photos.filter((photo) => !ids.includes(photo.id)),\n });\n }\n\n return undefined;\n }\n\n case 'draftMessage': {\n const {\n chatId, formattedText, date, replyingToId,\n } = update;\n const chat = global.chats.byId[chatId];\n if (!chat) {\n return undefined;\n }\n\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 return global;\n }\n\n case 'showInvite': {\n const { data } = update;\n\n actions.showDialog({ data });\n\n return undefined;\n }\n\n case 'updatePendingJoinRequests': {\n const { chatId, requestsPending, recentRequesterIds } = update;\n const chat = global.chats.byId[chatId];\n if (!chat) {\n return undefined;\n }\n\n global = updateChat(global, chatId, {\n fullInfo: {\n ...chat.fullInfo,\n requestsPending,\n recentRequesterIds,\n },\n });\n setGlobal(global);\n\n actions.loadChatJoinRequests({ chatId });\n }\n }\n\n return undefined;\n});\n","import { addActionHandler, getGlobal, setGlobal } from '../../index';\n\nimport {\n ApiMessage, ApiPollResult, ApiThreadInfo, MAIN_THREAD_ID,\n} from '../../../api/types';\n\nimport { unique } from '../../../util/iteratees';\nimport { areDeepEqual } from '../../../util/areDeepEqual';\nimport { notifyAboutMessage } from '../../../util/notifications';\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 { ActiveEmojiInteraction, GlobalActions, GlobalState } from '../../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 selectIsMessageInCurrentMessageList,\n selectScheduledIds,\n selectCurrentMessageList,\n selectViewportIds,\n selectFirstUnreadId,\n selectChat,\n selectIsChatWithBot,\n selectIsServiceChatReady,\n selectLocalAnimatedEmojiEffect,\n selectLocalAnimatedEmoji,\n} from '../../selectors';\nimport {\n getMessageContent, isUserId, isMessageLocal, getMessageText, checkIfReactionAdded,\n} from '../../helpers';\n\nconst ANIMATION_DELAY = 350;\n\naddActionHandler('apiUpdate', (global, actions, update) => {\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 (selectIsMessageInCurrentMessageList(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 'updateStartEmojiInteraction': {\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n if (currentChatId !== update.id) return;\n const message = selectChatMessage(global, currentChatId, update.messageId);\n\n if (!message) return;\n\n // Workaround for a weird behavior when interaction is received after watching reaction\n if (getMessageText(message) !== update.emoji) return;\n\n const localEmoji = selectLocalAnimatedEmoji(global, update.emoji);\n\n global = {\n ...global,\n activeEmojiInteractions: [...(global.activeEmojiInteractions || []), {\n id: global.activeEmojiInteractions?.length || 0,\n animatedEffect: localEmoji ? selectLocalAnimatedEmojiEffect(localEmoji) : update.emoji,\n messageId: update.messageId,\n } as ActiveEmojiInteraction],\n };\n\n setGlobal(global);\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 && selectIsMessageInCurrentMessageList(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 case 'updateMessageReactions': {\n const { chatId, id, reactions } = update;\n const message = selectChatMessage(global, chatId, id);\n const chat = selectChat(global, update.chatId);\n const currentReactions = message?.reactions;\n\n // `updateMessageReactions` happens with an interval, so we try to avoid redundant global state updates\n if (currentReactions && areDeepEqual(reactions, currentReactions)) {\n return;\n }\n\n // Only notify about added reactions, not removed ones\n const shouldNotify = checkIfReactionAdded(currentReactions, reactions, global.currentUserId);\n\n global = updateChatMessage(global, chatId, id, { reactions: update.reactions });\n\n if (shouldNotify) {\n const newMessage = selectChatMessage(global, chatId, id);\n if (!chat || !newMessage) return;\n notifyAboutMessage({\n chat,\n message: newMessage,\n isReaction: true,\n });\n }\n\n setGlobal(global);\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 candidateGlobal = addViewportId(global, chatId, MAIN_THREAD_ID, id);\n const newViewportIds = selectViewportIds(candidateGlobal, chatId, MAIN_THREAD_ID);\n\n if (!firstUnreadId || newViewportIds!.includes(firstUnreadId)) {\n global = candidateGlobal;\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 { addActionHandler, getGlobal, setGlobal } from '../../index';\n\nimport { 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\naddActionHandler('apiUpdate', (global, actions, update) => {\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 { addActionHandler } from '../../index';\n\nimport { updateStickerSet } from '../../reducers';\n\naddActionHandler('apiUpdate', (global, actions, update) => {\n switch (update['@type']) {\n case 'updateStickerSet': {\n return updateStickerSet(global, update.id, update.stickerSet);\n }\n }\n\n return undefined;\n});\n","import { addActionHandler, getGlobal, setGlobal } from '../../index';\n\nimport { ApiPrivacyKey, PaymentStep } from '../../../types';\n\nimport {\n addBlockedContact, removeBlockedContact, setConfirmPaymentUrl, setPaymentStep,\n} from '../../reducers';\n\naddActionHandler('apiUpdate', (global, actions, update) => {\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 case 'updatePaymentVerificationNeeded':\n global = setConfirmPaymentUrl(getGlobal(), update.url);\n global = setPaymentStep(global, PaymentStep.ConfirmPayment);\n setGlobal(global);\n break;\n }\n\n return undefined;\n});\n","import { addActionHandler, setGlobal } from '../../index';\n\nimport { addNotifyException, updateChat, updateNotifySettings } from '../../reducers';\n\naddActionHandler('apiUpdate', (global, actions, update) => {\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 { addActionHandler } from '../../index';\n\naddActionHandler('apiUpdate', (global, actions, update) => {\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 { addActionHandler, getGlobal } from '../../index';\nimport { removeGroupCall, updateGroupCall, updateGroupCallParticipant } from '../../reducers/calls';\nimport { omit } from '../../../util/iteratees';\nimport { selectChat } from '../../selectors';\nimport { updateChat } from '../../reducers';\n\naddActionHandler('apiUpdate', (global, actions, update) => {\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(\n global, groupCallId, participant.id, participant, Boolean(nextOffset) || currentUserId === participant.id,\n );\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 { addActionHandler } from '../../index';\n\nimport { clearPayment } from '../../reducers';\n\naddActionHandler('apiUpdate', (global, actions, update) => {\n switch (update['@type']) {\n case 'updatePaymentStateCompleted': {\n return clearPayment(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 React, { FC, memo, useEffect } from '../../lib/teact/teact';\n\nimport { formatIntegerCompact } from '../../util/textFormat';\nimport { useFolderManagerForUnreadCounters } from '../../hooks/useFolderManager';\nimport { getAllNotificationsCount } from '../../util/folderManager';\nimport { updateAppBadge } from '../../util/appBadge';\n\ninterface OwnProps {\n isForAppBadge?: boolean;\n}\n\nconst UnreadCounter: FC = ({ isForAppBadge }) => {\n useFolderManagerForUnreadCounters();\n const unreadNotificationsCount = getAllNotificationsCount();\n\n useEffect(() => {\n if (isForAppBadge) {\n updateAppBadge(unreadNotificationsCount);\n }\n }, [isForAppBadge, unreadNotificationsCount]);\n\n if (isForAppBadge || !unreadNotificationsCount) {\n return undefined;\n }\n\n return (\n
{formatIntegerCompact(unreadNotificationsCount)}
\n );\n};\n\nexport default memo(UnreadCounter);\n","import { GlobalState } from '../global/types';\n\nimport useBrowserOnline from './useBrowserOnline';\nimport { LangFn } from './useLang';\n\nexport enum ConnectionStatus {\n waitingForNetwork,\n syncing,\n online,\n}\n\ntype ConnectionStatusPosition =\n 'overlay'\n | 'minimized'\n | 'middleHeader'\n | 'none';\n\nexport default function useConnectionStatus(\n lang: LangFn,\n connectionState: GlobalState['connectionState'],\n isSyncing: GlobalState['isSyncing'],\n hasMiddleHeader: boolean,\n isMinimized?: boolean,\n isDisabled?: boolean,\n) {\n let status: ConnectionStatus;\n const isBrowserOnline = useBrowserOnline();\n if (!isBrowserOnline || connectionState === 'connectionStateConnecting') {\n status = ConnectionStatus.waitingForNetwork;\n } else if (isSyncing) {\n status = ConnectionStatus.syncing;\n } else {\n status = ConnectionStatus.online;\n }\n\n let position: ConnectionStatusPosition;\n if (status === ConnectionStatus.online || isDisabled) {\n position = 'none';\n } else if (hasMiddleHeader) {\n position = 'middleHeader';\n } else if (isMinimized) {\n position = 'minimized';\n } else {\n position = 'overlay';\n }\n\n let text: string | undefined;\n if (status === ConnectionStatus.waitingForNetwork) {\n text = lang('WaitingForNetwork');\n } else if (status === ConnectionStatus.syncing) {\n text = lang('Updating');\n }\n\n if (position === 'middleHeader') {\n text = text!.toLowerCase().replace(/\\.+$/, '');\n }\n\n return {\n connectionStatus: status,\n connectionStatusPosition: position,\n connectionStatusText: text,\n };\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, { FC, memo } from '../../lib/teact/teact';\n\nimport useLang from '../../hooks/useLang';\nimport { ConnectionStatus } from '../../hooks/useConnectionStatus';\n\nimport Transition from '../ui/Transition';\nimport Spinner from '../ui/Spinner';\nimport Button from '../ui/Button';\n\nimport './ConnectionStatusOverlay.scss';\n\ntype OwnProps = {\n connectionStatus: ConnectionStatus;\n connectionStatusText: string;\n onClick?: NoneToVoidFunction;\n};\n\nconst ConnectionStatusOverlay: FC = ({\n connectionStatus,\n connectionStatusText,\n onClick,\n}) => {\n const lang = useLang();\n\n return (\n
\n \n
\n \n {connectionStatusText}\n \n
\n \n \n \n
\n );\n};\n\nexport default memo(ConnectionStatusOverlay);\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../../global';\n\nimport { ISettings, LeftColumnContent } from '../../../types';\nimport { ApiChat } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\n\nimport {\n ANIMATION_LEVEL_MAX, APP_NAME, APP_VERSION, DEBUG, 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 { clearWebsync } from '../../../util/websync';\nimport { selectCurrentMessageList, selectTheme } from '../../../global/selectors';\nimport { isChatArchived } from '../../../global/helpers';\nimport useLang from '../../../hooks/useLang';\nimport { disableHistoryBack } from '../../../hooks/useHistoryBack';\nimport useConnectionStatus from '../../../hooks/useConnectionStatus';\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';\nimport ShowTransition from '../../ui/ShowTransition';\nimport ConnectionStatusOverlay from '../ConnectionStatusOverlay';\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 {\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 isMessageListOpen: boolean;\n isConnectionStatusMinimized: ISettings['isConnectionStatusMinimized'];\n areChatsLoaded?: boolean;\n }\n & Pick;\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 connectionState,\n isSyncing,\n isMessageListOpen,\n isConnectionStatusMinimized,\n areChatsLoaded,\n}) => {\n const {\n openChat,\n openTipsChat,\n setGlobalSearchDate,\n setSettingOption,\n setGlobalSearchChatId,\n } = getActions();\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 { connectionStatus, connectionStatusText, connectionStatusPosition } = useConnectionStatus(\n lang, connectionState, isSyncing, isMessageListOpen, isConnectionStatusMinimized, !areChatsLoaded,\n );\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 toggleConnectionStatus = useCallback(() => {\n setSettingOption({ isConnectionStatusMinimized: !isConnectionStatusMinimized });\n }, [isConnectionStatusMinimized, setSettingOption]);\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 clearWebsync();\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
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n query: searchQuery, fetchingStatus, chatId, date,\n } = global.globalSearch;\n const { currentUserId, connectionState, isSyncing } = global;\n const { byId: chatsById } = global.chats;\n const { isConnectionStatusMinimized, 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 connectionState,\n isSyncing,\n isMessageListOpen: Boolean(selectCurrentMessageList(global)),\n isConnectionStatusMinimized,\n areChatsLoaded: Boolean(global.chats.listIds.active),\n };\n },\n)(LeftMainHeader));\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef,\n} from '../../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../../global';\n\nimport { ApiChatFolder } from '../../../api/types';\nimport { SettingsScreens } from '../../../types';\nimport { FolderEditDispatch } from '../../../hooks/reducers/useFoldersReducer';\n\nimport { ALL_FOLDER_ID } from '../../../config';\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { captureEvents, SwipeDirection } from '../../../util/captureEvents';\nimport buildClassName from '../../../util/buildClassName';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useLang from '../../../hooks/useLang';\nimport useHistoryBack from '../../../hooks/useHistoryBack';\n\nimport Transition from '../../ui/Transition';\nimport TabList from '../../ui/TabList';\nimport ChatList from './ChatList';\nimport { useFolderManagerForUnreadCounters } from '../../../hooks/useFolderManager';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n foldersDispatch: FolderEditDispatch;\n};\n\ntype StateProps = {\n chatFoldersById: Record;\n orderedFolderIds?: number[];\n activeChatFolder: number;\n currentUserId?: string;\n lastSyncTime?: number;\n shouldSkipHistoryAnimations?: boolean;\n};\n\nconst SAVED_MESSAGES_HOTKEY = '0';\n\nconst ChatFolders: FC = ({\n foldersDispatch,\n onScreenSelect,\n chatFoldersById,\n orderedFolderIds,\n activeChatFolder,\n currentUserId,\n lastSyncTime,\n shouldSkipHistoryAnimations,\n}) => {\n const {\n loadChatFolders,\n setActiveChatFolder,\n openChat,\n } = getActions();\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 = useFolderManagerForUnreadCounters();\n const folderTabs = useMemo(() => {\n if (!displayedFolders || !displayedFolders.length) {\n return undefined;\n }\n\n return [\n {\n id: ALL_FOLDER_ID,\n title: lang.code === 'en' ? 'All' : lang('FilterAllChats'),\n },\n ...displayedFolders.map(({ id, title }) => ({\n id,\n title,\n badgeCount: folderCountersById[id]?.chatsCount,\n isBadgeActive: Boolean(folderCountersById[id]?.notificationsCount),\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 chatFolders: {\n byId: chatFoldersById,\n orderedIds: orderedFolderIds,\n activeChatFolder,\n },\n currentUserId,\n lastSyncTime,\n shouldSkipHistoryAnimations,\n } = global;\n\n return {\n chatFoldersById,\n orderedFolderIds,\n activeChatFolder,\n currentUserId,\n lastSyncTime,\n shouldSkipHistoryAnimations,\n };\n },\n)(ChatFolders));\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, 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\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 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, memo, useCallback, useEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { LeftColumnContent, SettingsScreens } from '../../../types';\nimport { FolderEditDispatch } from '../../../hooks/reducers/useFoldersReducer';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\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 ChatFolders from './ChatFolders';\nimport LeftSearch from '../search/LeftSearch.async';\nimport ContactList from './ContactList.async';\nimport NewChatButton from '../NewChatButton';\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\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}) => {\n const [isNewChatButtonShown, setIsNewChatButtonShown] = useState(IS_TOUCH_ENV);\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 {(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 memo(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 { getActions, withGlobal } from '../../global';\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 } = getActions();\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 case SettingsScreens.QuickReaction:\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 function 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 function handleMouseUp() {\n document.body.classList.remove('cursor-ew-resize');\n }\n\n function initResize(e: React.MouseEvent) {\n e.preventDefault();\n\n document.body.classList.add('cursor-ew-resize');\n\n setInitialMouseX(e.clientX);\n setInitialElementWidth(elementRef.current!.offsetWidth);\n markIsActive();\n }\n\n function resetResize(e: React.MouseEvent) {\n e.preventDefault();\n elementRef.current!.style.width = '';\n onReset();\n }\n\n useEffect(() => {\n if (!isActive) return undefined;\n\n const handleMouseMove = (e: MouseEvent) => {\n const newWidth = Math.ceil(initialElementWidth + e.clientX - initialMouseX);\n elementRef.current!.style.width = `${newWidth}px`;\n };\n\n function stopDrag() {\n cleanup();\n onResize(elementRef.current!.offsetWidth);\n }\n\n function cleanup() {\n handleMouseUp();\n document.removeEventListener('mousemove', handleMouseMove, false);\n document.removeEventListener('mouseup', stopDrag, false);\n document.removeEventListener('blur', stopDrag, false);\n unmarkIsActive();\n }\n\n document.addEventListener('mousemove', handleMouseMove, false);\n document.addEventListener('mouseup', stopDrag, false);\n document.addEventListener('blur', stopDrag, false);\n\n return cleanup;\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\nconst useCustomBackground = (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\nexport default useCustomBackground;\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\nconst useWindowSize = () => {\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\nexport default useWindowSize;\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 { getActions, withGlobal } from '../../global';\n\nimport { MessageListType } from '../../global/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\nimport { IAnchorPosition, ManagementScreens } 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 '../../global/helpers';\nimport {\n selectChat,\n selectChatBot,\n selectIsUserBlocked,\n selectIsChatBotNotStarted,\n selectIsChatWithSelf,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n} from '../../global/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 canViewStatistics?: boolean;\n canLeave?: boolean;\n canEnterVoiceChat?: boolean;\n canCreateVoiceChat?: boolean;\n pendingJoinRequests?: number;\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 canViewStatistics,\n canLeave,\n canEnterVoiceChat,\n canCreateVoiceChat,\n pendingJoinRequests,\n isRightColumnShown,\n canExpandActions,\n}) => {\n const {\n joinChannel,\n sendBotCommand,\n openLocalTextSearch,\n restartBot,\n openCallFallbackConfirm,\n requestNextManagementScreen,\n } = getActions();\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 handleJoinRequestsClick = useCallback(() => {\n requestNextManagementScreen({ screen: ManagementScreens.JoinRequests });\n }, [requestNextManagementScreen]);\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 {Boolean(pendingJoinRequests) && (\n \n \n
{pendingJoinRequests}
\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 const canViewStatistics = chat.fullInfo?.canViewStatistics;\n const pendingJoinRequests = chat.fullInfo?.requestsPending;\n\n return {\n noMenu: false,\n isChannel,\n isRightColumnShown,\n canStartBot,\n canRestartBot,\n canSubscribe,\n canSearch,\n canCall,\n canMute,\n canViewStatistics,\n canLeave,\n canEnterVoiceChat,\n canCreateVoiceChat,\n pendingJoinRequests,\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 '../global/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 } from '../../global/helpers';\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';\nimport { renderMessageSummary } from '../common/helpers/renderMessageText';\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 = renderMessageSummary(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

{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) => {\n if (!blob) throw new Error('Image resize failed!');\n return URL.createObjectURL(blob);\n })\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) => {\n if (!blob) throw new Error('Image resize failed!');\n return URL.createObjectURL(blob);\n })\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): Promise {\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 '../global/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\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\nconst useMessageMediaMetadata = (\n message: ApiMessage, sender?: ApiUser | ApiChat, chat?: ApiChat,\n): 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\nexport default useMessageMediaMetadata;\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 { getActions, withGlobal } from '../../global';\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 '../../global/helpers';\nimport { selectChat, selectSender } from '../../global/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 } = getActions();\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 { getActions, withGlobal } from '../../../global';\n\nimport { ApiChat, ApiGroupCall, ApiUser } from '../../../api/types';\n\nimport { selectChatGroupCall } from '../../../global/selectors/calls';\nimport buildClassName from '../../../util/buildClassName';\nimport { selectChat } from '../../../global/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 } = getActions();\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, memo, useCallback, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal, getActions } from '../../global';\n\nimport { ApiChat, ApiChatSettings, ApiUser } from '../../api/types';\n\nimport { selectChat, selectUser } from '../../global/selectors';\nimport {\n getChatTitle, getUserFirstOrLastName, getUserFullName, isChatBasicGroup, isUserId,\n} from '../../global/helpers';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\nimport useFlag from '../../hooks/useFlag';\n\nimport Button from '../ui/Button';\nimport ConfirmDialog from '../ui/ConfirmDialog';\nimport Checkbox from '../ui/Checkbox';\n\nimport './ChatReportPanel.scss';\n\ntype OwnProps = {\n chatId: string;\n className?: string;\n settings?: ApiChatSettings;\n};\n\ntype StateProps = {\n currentUserId?: string;\n chat?: ApiChat;\n user?: ApiUser;\n};\n\nconst ChatReportPanel: FC = ({\n chatId, className, chat, user, settings, currentUserId,\n}) => {\n const {\n openAddContactDialog,\n blockContact,\n reportSpam,\n deleteChat,\n leaveChannel,\n deleteChatUser,\n deleteHistory,\n toggleChatArchived,\n hideChatReportPanel,\n } = getActions();\n\n const lang = useLang();\n const [isBlockUserModalOpen, openBlockUserModal, closeBlockUserModal] = useFlag();\n const [shouldReportSpam, setShouldReportSpam] = useState(true);\n const [shouldDeleteChat, setShouldDeleteChat] = useState(true);\n const { accessHash } = chat || {};\n const {\n isAutoArchived, canReportSpam, canAddContact, canBlockContact,\n } = settings || {};\n const isBasicGroup = chat && isChatBasicGroup(chat);\n\n const handleAddContact = useCallback(() => {\n openAddContactDialog({ userId: chatId });\n if (isAutoArchived) {\n toggleChatArchived({ chatId });\n }\n }, [openAddContactDialog, isAutoArchived, toggleChatArchived, chatId]);\n\n const handleConfirmBlock = useCallback(() => {\n closeBlockUserModal();\n blockContact({ contactId: chatId, accessHash });\n if (canReportSpam && shouldReportSpam) {\n reportSpam({ chatId });\n }\n if (shouldDeleteChat) {\n deleteChat({ chatId });\n }\n }, [\n accessHash, blockContact, closeBlockUserModal, deleteChat, reportSpam, canReportSpam, shouldDeleteChat,\n shouldReportSpam, chatId,\n ]);\n\n const handleCloseReportPanel = useCallback(() => {\n hideChatReportPanel({ chatId });\n }, [chatId, hideChatReportPanel]);\n\n const handleChatReportSpam = useCallback(() => {\n closeBlockUserModal();\n reportSpam({ chatId });\n if (isBasicGroup) {\n deleteChatUser({ chatId, userId: currentUserId });\n deleteHistory({ chatId, shouldDeleteForAll: false });\n } else {\n leaveChannel({ chatId });\n }\n }, [\n chatId, closeBlockUserModal, currentUserId, deleteChatUser, deleteHistory, isBasicGroup, leaveChannel, reportSpam,\n ]);\n\n if (!settings) {\n return undefined;\n }\n\n return (\n
\n {canAddContact && (\n \n {lang('lng_new_contact_add')}\n \n )}\n {canBlockContact && (\n \n {lang('lng_new_contact_block')}\n \n )}\n {canReportSpam && !canBlockContact && (\n \n {lang('lng_report_spam_and_leave')}\n \n )}\n \n \n \n \n {user && canReportSpam && (\n \n )}\n {user && (\n \n )}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => ({\n currentUserId: global.currentUserId,\n chat: selectChat(global, chatId),\n user: isUserId(chatId) ? selectUser(global, chatId) : undefined,\n }),\n)(ChatReportPanel));\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../global';\nimport cycleRestrict from '../../util/cycleRestrict';\n\nimport { GlobalState, MessageListType } from '../../global/types';\nimport {\n ApiChat, ApiMessage, ApiTypingStatus, ApiUser, MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport {\n EDITABLE_INPUT_ID,\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n SAFE_SCREEN_WIDTH_FOR_CHAT_INFO,\n SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n} from '../../config';\nimport { IS_SINGLE_COLUMN_LAYOUT, IS_TABLET_COLUMN_LAYOUT } from '../../util/environment';\nimport {\n getChatTitle, getMessageKey, getSenderTitle, isUserId,\n} from '../../global/helpers';\nimport {\n selectAllowedMessageActions,\n selectChat,\n selectChatMessage,\n selectChatMessages,\n selectForwardedSender,\n selectIsChatWithBot,\n selectIsChatWithSelf,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n selectPinnedIds,\n selectScheduledIds,\n selectThreadInfo,\n selectThreadTopMessageId,\n} from '../../global/selectors';\nimport useEnsureMessage from '../../hooks/useEnsureMessage';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\nimport useConnectionStatus from '../../hooks/useConnectionStatus';\n\nimport PrivateChatInfo from '../common/PrivateChatInfo';\nimport GroupChatInfo from '../common/GroupChatInfo';\nimport UnreadCounter from '../common/UnreadCounter';\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';\nimport ChatReportPanel from './ChatReportPanel';\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 messagesCount?: number;\n isChatWithSelf?: boolean;\n isChatWithBot?: boolean;\n lastSyncTime?: number;\n shouldSkipHistoryAnimations?: boolean;\n currentTransitionKey: number;\n connectionState?: GlobalState['connectionState'];\n isSyncing?: GlobalState['isSyncing'];\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 messagesCount,\n isChatWithSelf,\n isChatWithBot,\n lastSyncTime,\n shouldSkipHistoryAnimations,\n currentTransitionKey,\n connectionState,\n isSyncing,\n}) => {\n const {\n openChatWithInfo,\n pinMessage,\n focusMessage,\n openChat,\n openPreviousChat,\n loadPinnedMessages,\n toggleLeftColumn,\n exitMessageSelectMode,\n } = getActions();\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 const { settings } = chat || {};\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 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 hasChatSettings = Boolean(settings?.canAddContact || settings?.canBlockContact || settings?.canReportSpam);\n const {\n shouldRender: shouldShowChatReportPanel,\n transitionClassNames: chatReportPanelClassNames,\n } = useShowTransition(hasChatSettings);\n const renderingChatSettings = useCurrentOrPrev(hasChatSettings ? settings : undefined, true);\n\n const {\n shouldRender: shouldRenderAudioPlayer,\n transitionClassNames: audioPlayerClassNames,\n } = useShowTransition(Boolean(audioMessage));\n\n const renderingAudioMessage = useCurrentOrPrev(audioMessage, true);\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 { connectionStatusText } = useConnectionStatus(lang, connectionState, isSyncing, true);\n\n function renderInfo() {\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, withUnreadCounter = false) {\n return (\n
\n \n
\n \n {withUnreadCounter && }\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 {shouldShowChatReportPanel && (\n \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 chat = selectChat(global, chatId);\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 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 isSyncing: global.isSyncing,\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 { getDayStartAt } from '../../../util/dateFormat';\nimport { isActionMessage } from '../../../global/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: getDayStartAt(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 = getDayStartAt(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 { getActions } from '../../../global';\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 } = getActions();\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 '../../../../global/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 hasReactions,\n isGeoLiveActive,\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 hasReactions?: boolean;\n isGeoLiveActive?: boolean;\n } = {},\n) {\n const {\n text, photo, video, audio, voice, document, poll, webPage, contact, location,\n } = getMessageContent(message);\n\n const classNames = ['message-content'];\n const isMedia = photo || video || location;\n const hasText = text || location?.type === 'venue' || isGeoLiveActive;\n const isMediaWithNoText = isMedia && !hasText;\n const isViaBot = Boolean(message.viaBotId);\n\n if (isEmojiOnlyMessage(customShape)) {\n classNames.push(`emoji-only emoji-only-${customShape}`);\n } else if (hasText) {\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 (isMedia) {\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 (hasReactions) {\n classNames.push('has-reactions');\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 || (location && !hasText) || !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 '../../../../global/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 { RefObject } from 'react';\nimport React, { useEffect, useRef } from '../../../../lib/teact/teact';\nimport { getActions } from '../../../../global';\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';\nimport { REM } from '../../../common/helpers/mediaDimensions';\n\nconst ANDROID_KEYBOARD_HIDE_DELAY_MS = 350;\nconst SWIPE_ANIMATION_DURATION = 150;\nconst QUICK_REACTION_DOUBLE_TAP_DELAY = 200;\nconst QUICK_REACTION_AREA_WIDTH = 3 * REM;\nconst QUICK_REACTION_AREA_HEIGHT = Number(REM);\nconst GROUP_MESSAGE_HOVER_ATTRIBUTE = 'data-is-document-group-hover';\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 chatId: string,\n isContextMenuShown: boolean,\n contentRef: RefObject,\n isOwn: boolean,\n shouldHandleMouseLeave: boolean,\n) {\n const { setReplyingToId, sendDefaultReaction } = getActions();\n\n const [isQuickReactionVisible, markQuickReactionVisible, unmarkQuickReactionVisible] = useFlag();\n const [isSwiped, markSwiped, unmarkSwiped] = useFlag();\n const doubleTapTimeoutRef = useRef();\n\n function handleMouseDown(e: React.MouseEvent) {\n preventMessageInputBlur(e);\n handleBeforeContextMenu(e);\n }\n\n function handleMouseMove(e: React.MouseEvent) {\n const container = contentRef.current;\n if (!container) return;\n\n const { clientX, clientY } = e;\n const {\n x, width, y, height,\n } = container.getBoundingClientRect();\n\n const isVisibleX = Math.abs((isOwn ? (clientX - x) : (x + width - clientX))) < QUICK_REACTION_AREA_WIDTH;\n const isVisibleY = Math.abs(y + height - clientY) < QUICK_REACTION_AREA_HEIGHT;\n if (isVisibleX && isVisibleY) {\n markQuickReactionVisible();\n } else {\n unmarkQuickReactionVisible();\n }\n }\n\n function handleSendQuickReaction(e: React.MouseEvent) {\n const { x, y } = e.currentTarget.getBoundingClientRect();\n sendDefaultReaction({\n chatId,\n messageId,\n x,\n y,\n });\n }\n\n function handleTap(e: React.MouseEvent) {\n 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 handleDoubleTap(e: React.MouseEvent) {\n const { pageX: x, pageY: y } = e;\n\n sendDefaultReaction({\n chatId,\n messageId,\n x,\n y,\n });\n }\n\n function handleClick(e: React.MouseEvent) {\n if (isInSelectMode) {\n selectMessage(e);\n return;\n }\n\n if (!IS_TOUCH_ENV) return;\n\n if (doubleTapTimeoutRef.current) {\n clearInterval(doubleTapTimeoutRef.current);\n doubleTapTimeoutRef.current = undefined;\n handleDoubleTap(e);\n return;\n }\n\n doubleTapTimeoutRef.current = setTimeout(() => {\n doubleTapTimeoutRef.current = undefined;\n handleTap(e);\n }, QUICK_REACTION_DOUBLE_TAP_DELAY);\n }\n\n function handleContextMenu(e: React.MouseEvent) {\n if (IS_ANDROID) {\n if ((e.target as HTMLElement).matches('a[href]') || isContextMenuShown) {\n return;\n }\n\n e.preventDefault();\n selectMessage();\n } else {\n onContextMenu(e);\n }\n }\n\n function handleContainerDoubleClick() {\n if (IS_TOUCH_ENV) return;\n\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 || isContextMenuShown) {\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 }, [\n containerRef, isInSelectMode, messageId, setReplyingToId, markSwiped, unmarkSwiped, canReply, isContextMenuShown,\n ]);\n\n function handleMouseLeave(e: React.MouseEvent) {\n unmarkQuickReactionVisible();\n if (shouldHandleMouseLeave) handleDocumentGroupMouseLeave(e);\n }\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 handleMouseMove,\n handleSendQuickReaction,\n handleMouseLeave,\n isSwiped,\n isQuickReactionVisible,\n handleDocumentGroupMouseEnter,\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","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 '../../global';\n\nimport { ApiUser, ApiMessage, ApiChat } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport {\n selectUser,\n selectChatMessage,\n selectIsMessageFocused,\n selectChat,\n} from '../../global/selectors';\nimport { getMessageHtmlId, isChatChannel } from '../../global/helpers';\nimport buildClassName from '../../util/buildClassName';\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 senderUser?: ApiUser;\n senderChat?: 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 senderUser,\n senderChat,\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 senderUser,\n senderChat,\n targetUsers,\n targetMessage,\n targetChatId,\n { asTextWithSpoilers: isEmbedded },\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 {content};\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 isChat = chat && (isChatChannel(chat) || userId === message.chatId);\n const senderUser = !isChat && userId ? selectUser(global, userId) : undefined;\n const senderChat = isChat ? chat : undefined;\n\n return {\n usersById,\n senderUser,\n senderChat,\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 getSenderTitle,\n getMessageRoundVideo,\n} from '../../global/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';\nimport { renderMessageSummary } from './helpers/renderMessageText';\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 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(mediaThumbnail, mediaBlobUrl, isRoundVideo, isProtected)}\n
\n

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

\n
{renderText(senderTitle || title || NBSP)}
\n
\n \n );\n};\n\nfunction renderPictogram(\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, { FC, memo, useCallback } from '../../../lib/teact/teact';\nimport { getActions } from '../../../global';\n\nimport { ActiveReaction } from '../../../global/types';\nimport { ApiAvailableReaction, ApiMediaFormat } from '../../../api/types';\n\nimport buildClassName from '../../../util/buildClassName';\nimport useMedia from '../../../hooks/useMedia';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useFlag from '../../../hooks/useFlag';\n\nimport ReactionStaticEmoji from '../../common/ReactionStaticEmoji';\nimport AnimatedSticker from '../../common/AnimatedSticker';\n\nimport './ReactionAnimatedEmoji.scss';\n\ntype OwnProps = {\n reaction: string;\n activeReaction?: ActiveReaction;\n isInMeta?: boolean;\n availableReactions?: ApiAvailableReaction[];\n};\n\nconst CENTER_ICON_SIZE = 30;\nconst EFFECT_SIZE = 100;\n\nconst ReactionAnimatedEmoji: FC = ({\n reaction,\n activeReaction,\n isInMeta,\n availableReactions,\n}) => {\n const { stopActiveReaction } = getActions();\n\n const availableReaction = availableReactions?.find((r) => r.reaction === reaction);\n const centerIconId = availableReaction?.centerIcon?.id;\n const effectId = availableReaction?.aroundAnimation?.id;\n const mediaDataCenterIcon = useMedia(`sticker${centerIconId}`, !centerIconId, ApiMediaFormat.Lottie);\n const mediaDataEffect = useMedia(`sticker${effectId}`, !effectId, ApiMediaFormat.Lottie);\n\n const shouldPlay = Boolean(activeReaction?.reaction === reaction && mediaDataCenterIcon && mediaDataEffect);\n const {\n shouldRender: shouldRenderAnimation,\n transitionClassNames: animationClassNames,\n } = useShowTransition(shouldPlay, undefined, true, 'slow');\n\n const handleEnded = useCallback(() => {\n stopActiveReaction({ messageId: activeReaction?.messageId, reaction });\n }, [activeReaction?.messageId, reaction, stopActiveReaction]);\n\n const [isAnimationLoaded, markAnimationLoaded, unmarkAnimationLoaded] = useFlag();\n const shouldRenderStatic = !shouldPlay || !isAnimationLoaded;\n\n const className = buildClassName(\n 'ReactionAnimatedEmoji',\n isInMeta && 'in-meta',\n shouldRenderAnimation && 'is-animating',\n );\n\n return (\n
\n {shouldRenderStatic && }\n {shouldRenderAnimation && (\n <>\n \n \n \n )}\n
\n );\n};\n\nexport default memo(ReactionAnimatedEmoji);\n","import React, {\n FC, memo, useMemo,\n} from '../../../lib/teact/teact';\n\nimport { ApiAvailableReaction, ApiMessage, ApiMessageOutgoingStatus } from '../../../api/types';\nimport { ActiveReaction } from '../../../global/types';\n\nimport { formatDateTimeToString, formatTime } from '../../../util/dateFormat';\nimport { formatIntegerCompact } from '../../../util/textFormat';\n\nimport renderText from '../../common/helpers/renderText';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\nimport buildClassName from '../../../util/buildClassName';\n\nimport MessageOutgoingStatus from '../../common/MessageOutgoingStatus';\nimport ReactionAnimatedEmoji from './ReactionAnimatedEmoji';\n\nimport './MessageMeta.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n reactionMessage?: ApiMessage;\n withReactions?: boolean;\n withReactionOffset?: boolean;\n outgoingStatus?: ApiMessageOutgoingStatus;\n signature?: string;\n onClick: (e: React.MouseEvent) => void;\n activeReaction?: ActiveReaction;\n availableReactions?: ApiAvailableReaction[];\n};\n\nconst MessageMeta: FC = ({\n message, outgoingStatus, signature, onClick, withReactions,\n activeReaction, withReactionOffset, availableReactions,\n reactionMessage,\n}) => {\n const lang = useLang();\n const [isActivated, markActivated] = useFlag();\n\n const reactions = withReactions && reactionMessage?.reactions?.results.filter((l) => l.count > 0);\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 {reactions && reactions.map((l) => (\n \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(lang, message.date * 1000)}\n \n {outgoingStatus && (\n \n )}\n
\n );\n};\n\nexport default memo(MessageMeta);\n","import React, { FC, useEffect, useRef } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { NO_STICKER_SET_ID } from '../../../config';\nimport { getStickerDimensions } from '../../common/helpers/mediaDimensions';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../global/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';\nimport safePlay from '../../../util/safePlay';\nimport { IS_WEBM_SUPPORTED } from '../../../util/environment';\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 { isLottie, stickerSetId, isVideo } = sticker;\n const canDisplayVideo = IS_WEBM_SUPPORTED;\n const isMemojiSticker = stickerSetId === NO_STICKER_SET_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 previewMediaHash = isVideo && !canDisplayVideo && (\n sticker.isPreloadedGlobally ? `sticker${sticker.id}?size=m` : getMessageMediaHash(message, 'pictogram'));\n const previewBlobUrl = useMedia(previewMediaHash);\n const thumbDataUri = useWebpThumbnail(message);\n const previewUrl = previewBlobUrl || thumbDataUri;\n\n const mediaData = useMedia(\n mediaHash,\n !shouldLoad,\n getMessageMediaFormat(message, 'inline'),\n lastSyncTime,\n );\n\n const isMediaLoaded = Boolean(mediaData);\n const [isLottieLoaded, markLottieLoaded] = useFlag(isMediaLoaded);\n const isMediaReady = isLottie ? isLottieLoaded : 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 useEffect(() => {\n if (!isVideo || !ref.current) return;\n const video = ref.current.querySelector('video');\n if (!video) return;\n if (shouldPlay) {\n safePlay(video);\n } else {\n video.pause();\n }\n }, [isVideo, shouldPlay]);\n\n return (\n
\n {(!isMediaReady || (isVideo && !canDisplayVideo)) && (\n \n )}\n {!isLottie && !isVideo && (\n \n )}\n {isVideo && canDisplayVideo && isMediaReady && (\n \n )}\n {isLottie && 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 '../../../../global/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 { CUSTOM_APPENDIX_ATTRIBUTE } from '../../../config';\nimport {\n getMessagePhoto,\n getMessageWebPagePhoto,\n getMessageMediaHash,\n getMediaTransferState,\n isOwnMessage,\n} from '../../../global/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 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 { getActions } from '../../../global';\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 '../../../global/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 getActions().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 { getActions, withGlobal } from '../../../global';\n\nimport { ApiUser, ApiContact, ApiCountryCode } from '../../../api/types';\n\nimport { selectUser } from '../../../global/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 { openChat } = getActions();\n\n const {\n firstName,\n lastName,\n phoneNumber,\n userId,\n } = contact;\n\n const handleClick = useCallback(() => {\n openChat({ id: userId });\n }, [openChat, 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 { getActions, withGlobal } from '../../../global';\n\nimport {\n ApiMessage, ApiPoll, ApiUser, ApiPollAnswer,\n} from '../../../api/types';\n\nimport renderText from '../../common/helpers/renderText';\nimport { renderTextWithEntities } from '../../common/helpers/renderTextWithEntities';\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 } = getActions();\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 '../../../global/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 '../../../global/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","const PROVIDER = 'http://maps.google.com/maps';\n\n// eslint-disable-next-line max-len\n// https://github.com/TelegramMessenger/Telegram-iOS/blob/2a32c871882c4e1b1ccdecd34fccd301723b30d9/submodules/LocationResources/Sources/VenueIconResources.swift#L82\nconst VENUE_COLORS = new Map(Object.entries({\n 'building/medical': '#43b3f4',\n 'building/gym': '#43b3f4',\n 'education/cafeteria': '#f7943f',\n 'travel/bedandbreakfast': '#9987ff',\n 'travel/hotel': '#9987ff',\n 'travel/hostel': '#9987ff',\n 'travel/resort': '#9987ff',\n 'travel/hotel_bar': '#e56dd6',\n arts_entertainment: '#e56dd6',\n building: '#6e81b2',\n education: '#a57348',\n event: '#959595',\n food: '#f7943f',\n home: '#00aeef',\n nightlife: '#e56dd6',\n parks_outdoors: '#6cc039',\n shops: '#ffb300',\n travel: '#1c9fff',\n work: '#ad7854',\n}));\n\nconst RANDOM_COLORS = [\n '#e56cd5', '#f89440', '#9986ff', '#44b3f5', '#6dc139', '#ff5d5a', '#f87aad', '#6e82b3', '#f5ba21',\n];\n\nexport function prepareMapUrl(lat: number, long: number, zoom: number) {\n return `${PROVIDER}/place/${lat}+${long}/@${lat},${long},${zoom}z`;\n}\n\nexport function getMetersPerPixel(lat: number, zoom: number) {\n // https://groups.google.com/g/google-maps-js-api-v3/c/hDRO4oHVSeM/m/osOYQYXg2oUJ\n return (156543.03392 * Math.cos(lat * (Math.PI / 180))) / 2 ** zoom;\n}\n\nexport function getVenueIconUrl(type?: string) {\n if (!type) return '';\n return `https://ss3.4sqi.net/img/categories_v2/${type}_88.png`;\n}\n\n// eslint-disable-next-line max-len\n// https://github.com/TelegramMessenger/Telegram-iOS/blob/2a32c871882c4e1b1ccdecd34fccd301723b30d9/submodules/LocationResources/Sources/VenueIconResources.swift#L104\nexport function getVenueColor(type?: string) {\n if (!type) return '#008df2';\n return VENUE_COLORS.get(type)\n || VENUE_COLORS.get(type.split('/')[0])\n || RANDOM_COLORS[stringToNumber(type) % RANDOM_COLORS.length];\n}\n\nfunction stringToNumber(str: string) {\n return str.split('').reduce((prevHash, currVal) => (\n // eslint-disable-next-line no-bitwise\n (((prevHash << 5) - prevHash) + currVal.charCodeAt(0)) | 0), 0);\n}\n","import React, { FC } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Skeleton.scss';\n\ntype OwnProps = {\n variant?: 'rectangular' | 'rounded-rect' | 'round';\n animation?: 'wave' | 'pulse';\n width?: number;\n height?: number;\n className?: string;\n};\n\nconst Skeleton: FC = ({\n variant = 'rectangular', animation = 'wave', width, height, className,\n}) => {\n const classNames = buildClassName('Skeleton', variant, animation, className);\n const style = (width ? `width: ${width}px;` : '') + (height ? `height: ${height}px;` : '');\n return (\n
\n );\n};\n\nexport default Skeleton;\n","import React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiChat, ApiMessage, ApiUser } from '../../../api/types';\nimport { ISettings } from '../../../types';\n\nimport { CUSTOM_APPENDIX_ATTRIBUTE } from '../../../config';\nimport {\n getMessageLocation,\n buildStaticMapHash,\n isGeoLiveExpired,\n isOwnMessage,\n isUserId,\n} from '../../../global/helpers';\nimport useMedia from '../../../hooks/useMedia';\nimport getCustomAppendixBg from './helpers/getCustomAppendixBg';\nimport { formatCountdownShort, formatLastUpdated } from '../../../util/dateFormat';\nimport useLang from '../../../hooks/useLang';\nimport useForceUpdate from '../../../hooks/useForceUpdate';\nimport useTimeout from '../../../hooks/useTimeout';\nimport {\n getMetersPerPixel, getVenueColor, getVenueIconUrl, prepareMapUrl,\n} from '../../../util/map';\nimport buildClassName from '../../../util/buildClassName';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useInterval from '../../../hooks/useInterval';\nimport { getServerTime } from '../../../util/serverTime';\n\nimport Avatar from '../../common/Avatar';\nimport Skeleton from '../../ui/Skeleton';\n\nimport mapPin from '../../../assets/map-pin.svg';\nimport './Location.scss';\n\nconst MOVE_THRESHOLD = 0.0001; // ~11m\nconst DEFAULT_MAP_CONFIG = {\n width: 400,\n height: 300,\n zoom: 16,\n scale: 2,\n};\n\n// eslint-disable-next-line max-len\nconst SVG_PIN = { __html: '' };\n\ntype OwnProps = {\n message: ApiMessage;\n peer?: ApiUser | ApiChat;\n lastSyncTime?: number;\n isInSelectMode?: boolean;\n isSelected?: boolean;\n theme: ISettings['theme'];\n serverTimeOffset: number;\n};\n\nconst Location: FC = ({\n message,\n peer,\n lastSyncTime,\n isInSelectMode,\n isSelected,\n theme,\n serverTimeOffset,\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 countdownRef = useRef(null);\n const lang = useLang();\n const forceUpdate = useForceUpdate();\n\n const location = getMessageLocation(message)!;\n const { type, geo } = location;\n\n const serverTime = getServerTime(serverTimeOffset);\n const isExpired = isGeoLiveExpired(message, serverTime);\n const secondsBeforeEnd = (type === 'geoLive' && !isExpired) ? message.date + location.period - serverTime\n : undefined;\n\n const [point, setPoint] = useState(geo);\n\n const shouldRenderText = type === 'venue' || (type === 'geoLive' && !isExpired);\n const {\n width, height, zoom, scale,\n } = DEFAULT_MAP_CONFIG;\n\n const mediaHash = Boolean(lastSyncTime) && buildStaticMapHash(point, width, height, zoom, scale);\n const mediaBlobUrl = useMedia(mediaHash);\n const prevMediaBlobUrl = usePrevious(mediaBlobUrl);\n const mapBlobUrl = mediaBlobUrl || prevMediaBlobUrl;\n\n const isPeerUser = peer && isUserId(peer.id);\n const avatarUser = (peer && isPeerUser) ? peer as ApiUser : undefined;\n const avatarChat = (peer && !isPeerUser) ? peer as ApiChat : undefined;\n\n const isOwn = isOwnMessage(message);\n\n const accuracyRadiusPx = useMemo(() => {\n if (type !== 'geoLive' || !point.accuracyRadius) {\n return 0;\n }\n\n const { lat, accuracyRadius } = point;\n return accuracyRadius / getMetersPerPixel(lat, zoom);\n }, [type, point, zoom]);\n\n const handleClick = () => {\n const url = prepareMapUrl(point.lat, point.long, zoom);\n window.open(url, '_blank')?.focus();\n };\n\n const updateCountdown = useCallback((countdownEl: HTMLDivElement) => {\n if (type !== 'geoLive') return;\n const radius = 12;\n const circumference = radius * 2 * Math.PI;\n const svgEl = countdownEl.lastElementChild;\n const timerEl = countdownEl.firstElementChild as SVGElement;\n\n const timeLeft = message.date + location.period - getServerTime(serverTimeOffset);\n const strokeDashOffset = (1 - timeLeft / location.period) * circumference;\n const text = formatCountdownShort(lang, timeLeft * 1000);\n\n if (!svgEl || !timerEl) {\n countdownEl.innerHTML = `\n ${text}\n \n \n `;\n } else {\n timerEl.textContent = text;\n svgEl.firstElementChild!.setAttribute('stroke-dashoffset', `-${strokeDashOffset}`);\n }\n }, [type, message.date, location, serverTimeOffset, lang]);\n\n useLayoutEffect(() => {\n if (countdownRef.current) {\n updateCountdown(countdownRef.current);\n }\n }, [updateCountdown]);\n\n useLayoutEffect(() => {\n if (shouldRenderText) return;\n const contentEl = ref.current!.closest('.message-content')!;\n if (mapBlobUrl) {\n getCustomAppendixBg(mapBlobUrl, isOwn, isInSelectMode, isSelected, theme).then((appendixBg) => {\n contentEl.style.setProperty('--appendix-bg', appendixBg);\n contentEl.classList.add('has-appendix-thumb');\n contentEl.setAttribute(CUSTOM_APPENDIX_ATTRIBUTE, '');\n });\n }\n }, [isOwn, isInSelectMode, isSelected, theme, mapBlobUrl, shouldRenderText]);\n\n useEffect(() => {\n // Prevent map refetching for slight location changes\n if (Math.abs(geo.lat - point.lat) < MOVE_THRESHOLD && Math.abs(geo.long - point.long) < MOVE_THRESHOLD) {\n if (point.accuracyRadius !== geo.accuracyRadius) {\n setPoint({\n ...point,\n accuracyRadius: geo.accuracyRadius,\n });\n }\n return;\n }\n setPoint(geo);\n }, [geo, point]);\n\n useTimeout(() => {\n forceUpdate();\n }, !isExpired ? (secondsBeforeEnd || 0) * 1000 : undefined);\n\n useInterval(() => {\n const countdownEl = countdownRef.current;\n\n if (countdownEl) {\n updateCountdown(countdownEl);\n }\n }, secondsBeforeEnd ? 1000 : undefined);\n\n function renderInfo() {\n if (!shouldRenderText) return undefined;\n if (type === 'venue') {\n return (\n
\n
\n {location.title}\n
\n
\n {location.address}\n
\n
\n );\n }\n if (type === 'geoLive') {\n return (\n
\n
{lang('AttachLiveLocation')}
\n
\n {formatLastUpdated(lang, serverTime, message.editDate)}\n
\n {!isExpired &&
}\n
\n );\n }\n return undefined;\n }\n\n function renderMap() {\n if (!mapBlobUrl) return ;\n return (\n \n );\n }\n\n function renderPin() {\n const pinClassName = buildClassName(\n 'pin',\n type,\n isExpired && 'expired',\n );\n if (type === 'geoLive') {\n return (\n
\n \n {location.heading !== undefined && (\n
\n )}\n
\n );\n }\n\n if (type === 'venue') {\n const color = getVenueColor(location.venueType);\n const icon = getVenueIconUrl(location.venueType);\n return (\n
\n \"\"\n
\n );\n }\n\n return (\n \"\"\n );\n }\n\n function renderOverlay() {\n if (!mapBlobUrl) return undefined;\n\n return (\n <>\n {Boolean(accuracyRadiusPx) && !isExpired && (\n \n )}\n {renderPin()}\n \n );\n }\n\n return (\n \n
\n {renderMap()}\n {renderOverlay()}\n
\n {renderInfo()}\n
\n );\n};\n\nexport default memo(Location);\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC,\n useCallback,\n useMemo,\n memo,\n} from '../../../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../../../global';\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 '../../../../global/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 } = getActions();\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 const { dimensions: dims, onClick } = props;\n return {\n ...props,\n isInSelectMode,\n isSelected,\n dimensions: {\n ...dims,\n x: 0,\n y: 0,\n },\n onClick: isInSelectMode ? undefined : 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, getMessageHtmlId } from '../../../global/helpers';\nimport { getActions, getGlobal, withGlobal } from '../../../global';\nimport withSelectControl from './hocs/withSelectControl';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\nimport {\n selectActiveDownloadIds,\n selectCanAutoLoadMedia,\n selectCanAutoPlayMedia,\n selectTheme,\n} from '../../../global/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 } = getActions();\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 { getActions } from '../../../global';\n\nimport { ApiMediaFormat, ApiMessage } from '../../../api/types';\n\nimport { ROUND_VIDEO_DIMENSIONS_PX } from '../../common/helpers/mediaDimensions';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../global/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 stopPrevious: NoneToVoidFunction;\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 = useCallback(() => {\n if (!playerRef.current) {\n return;\n }\n\n setIsActivated(false);\n setProgress(0);\n safePlay(playerRef.current);\n\n fastRaf(() => {\n playingProgressRef.current!.innerHTML = '';\n });\n }, []);\n\n const capturePlaying = useCallback(() => {\n stopPrevious?.();\n stopPrevious = stopPlaying;\n }, [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 getActions().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 { getActions, getGlobal } from '../../../global';\n\nimport {\n ApiChat, ApiThreadInfo, ApiUser,\n} from '../../../api/types';\n\nimport { isUserId } from '../../../global/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 } = getActions();\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, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { getActions, getGlobal } from '../../../global';\n\nimport {\n ApiAvailableReaction, ApiMessage, ApiReactionCount, ApiUser,\n} from '../../../api/types';\nimport { ActiveReaction } from '../../../global/types';\n\nimport buildClassName from '../../../util/buildClassName';\nimport { formatIntegerCompact } from '../../../util/textFormat';\n\nimport Button from '../../ui/Button';\nimport Avatar from '../../common/Avatar';\nimport ReactionAnimatedEmoji from './ReactionAnimatedEmoji';\n\nimport './Reactions.scss';\n\nconst MAX_REACTORS_AVATARS = 3;\n\nconst ReactionButton: FC<{\n reaction: ApiReactionCount;\n message: ApiMessage;\n activeReaction?: ActiveReaction;\n availableReactions?: ApiAvailableReaction[];\n}> = ({\n reaction,\n message,\n activeReaction,\n availableReactions,\n}) => {\n const { sendReaction } = getActions();\n\n const { recentReactions } = message.reactions!;\n\n const recentReactors = useMemo(() => {\n if (!recentReactions || reaction.count > MAX_REACTORS_AVATARS) {\n return undefined;\n }\n\n // No need for expensive global updates on users, so we avoid them\n const usersById = getGlobal().users.byId;\n\n return recentReactions\n .filter((recentReaction) => recentReaction.reaction === reaction.reaction)\n .map((recentReaction) => usersById[recentReaction.userId])\n .filter(Boolean) as ApiUser[];\n }, [reaction, recentReactions]);\n\n const handleClick = useCallback(() => {\n sendReaction({\n reaction: reaction.isChosen ? undefined : reaction.reaction,\n chatId: message.chatId,\n messageId: message.id,\n });\n }, [message, reaction, sendReaction]);\n\n return (\n \n \n {recentReactors?.length ? (\n
\n {recentReactors.map((user) => )}\n
\n ) : formatIntegerCompact(reaction.count)}\n \n );\n};\n\nexport default memo(ReactionButton);\n","import React, { FC, memo } from '../../../lib/teact/teact';\n\nimport { ApiAvailableReaction, ApiMessage } from '../../../api/types';\nimport { ActiveReaction } from '../../../global/types';\n\nimport buildClassName from '../../../util/buildClassName';\n\nimport ReactionButton from './ReactionButton';\n\nimport './Reactions.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n isOutside?: boolean;\n activeReaction?: ActiveReaction;\n availableReactions?: ApiAvailableReaction[];\n metaChildren?: React.ReactNode;\n};\n\nconst Reactions: FC = ({\n message,\n isOutside,\n activeReaction,\n availableReactions,\n metaChildren,\n}) => {\n return (\n
\n {message.reactions!.results.map((reaction) => (\n \n ))}\n {metaChildren}\n
\n );\n};\n\nexport default memo(Reactions);\n","import React, {\n FC, memo, useEffect, useState,\n} from '../../lib/teact/teact';\n\nimport { ActiveEmojiInteraction } from '../../global/types';\n\nimport { ObserveFn, useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport getAnimationData, { ANIMATED_STICKERS_PATHS } from './helpers/animatedAssets';\nimport useAnimatedEmoji from './hooks/useAnimatedEmoji';\n\nimport AnimatedSticker from './AnimatedSticker';\n\nconst QUALITY = 1;\n\ntype OwnProps = {\n localSticker?: string;\n localEffect?: string;\n isOwn?: boolean;\n soundId?: string;\n observeIntersection?: ObserveFn;\n size?: 'large' | 'medium' | 'small';\n lastSyncTime?: number;\n forceLoadPreview?: boolean;\n messageId?: number;\n chatId?: string;\n activeEmojiInteractions?: ActiveEmojiInteraction[];\n};\n\nconst LocalAnimatedEmoji: FC = ({\n localSticker,\n localEffect,\n isOwn,\n soundId,\n size = 'medium',\n observeIntersection,\n messageId,\n chatId,\n activeEmojiInteractions,\n}) => {\n const {\n playKey,\n ref,\n style,\n width,\n handleClick,\n markAnimationLoaded,\n } = useAnimatedEmoji(size, chatId, messageId, soundId, activeEmojiInteractions, isOwn, localEffect);\n const id = `local_emoji_${localSticker}`;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [localStickerAnimationData, setLocalStickerAnimationData] = useState();\n useEffect(() => {\n if (localSticker) {\n getAnimationData(localSticker as keyof typeof ANIMATED_STICKERS_PATHS).then((data) => {\n setLocalStickerAnimationData(data);\n });\n }\n }, [localSticker]);\n\n return (\n \n {localStickerAnimationData && (\n \n )}\n \n );\n};\n\nexport default memo(LocalAnimatedEmoji);\n","import React, {\n FC,\n memo,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n} from '../../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../../global';\n\nimport { ActiveEmojiInteraction, ActiveReaction, MessageListType } from '../../../global/types';\nimport {\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n ApiChat,\n ApiSticker,\n ApiThreadInfo,\n ApiAvailableReaction,\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 selectAnimatedEmojiEffect,\n selectAnimatedEmojiSound,\n selectMessageIdsByGroupId,\n selectLocalAnimatedEmoji,\n selectIsMessageProtected,\n selectLocalAnimatedEmojiEffect,\n selectDefaultReaction,\n} from '../../../global/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 areReactionsEmpty,\n getMessageHtmlId,\n isGeoLiveExpired,\n} from '../../../global/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';\nimport { getServerTime } from '../../../util/serverTime';\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 Location from './Location';\nimport Album from './Album';\nimport RoundVideo from './RoundVideo';\nimport InlineButtons from './InlineButtons';\nimport CommentButton from './CommentButton';\nimport Reactions from './Reactions';\nimport ReactionStaticEmoji from '../../common/ReactionStaticEmoji';\nimport LocalAnimatedEmoji from '../../common/LocalAnimatedEmoji';\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 areReactionsInMeta?: 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 canShowSender: boolean;\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 isInDocumentGroup: boolean;\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 serverTimeOffset: number;\n highlight?: string;\n isSingleEmoji?: boolean;\n animatedEmoji?: ApiSticker;\n localSticker?: string;\n localEffect?: string;\n animatedEmojiEffect?: ApiSticker;\n animatedEmojiSoundId?: string;\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 reactionMessage?: ApiMessage;\n availableReactions?: ApiAvailableReaction[];\n defaultReaction?: string;\n activeReaction?: ActiveReaction;\n activeEmojiInteractions?: ActiveEmojiInteraction[];\n};\n\ntype MetaPosition =\n 'in-text'\n | 'standalone'\n | 'none';\ntype ReactionsPosition =\n 'inside'\n | 'outside'\n | 'in-meta'\n | 'none';\n\nconst NBSP = '\\u00A0';\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 areReactionsInMeta,\n noComments,\n appearanceOrder,\n isFirstInGroup,\n isLastInGroup,\n isFirstInDocumentGroup,\n isLastInDocumentGroup,\n isLastInList,\n theme,\n forceSenderName,\n sender,\n canShowSender,\n originSender,\n botSender,\n isThreadTop,\n shouldHideReply,\n replyMessage,\n replyMessageSender,\n outgoingStatus,\n uploadProgress,\n isInDocumentGroup,\n isProtected,\n isFocused,\n focusDirection,\n noFocusHighlight,\n isResizingContainer,\n isForwarding,\n isChatWithSelf,\n isRepliesChat,\n isChannel,\n canReply,\n lastSyncTime,\n serverTimeOffset,\n highlight,\n animatedEmoji,\n localSticker,\n localEffect,\n animatedEmojiEffect,\n animatedEmojiSoundId,\n isInSelectMode,\n isSelected,\n isGroupSelected,\n threadId,\n reactionMessage,\n availableReactions,\n defaultReaction,\n activeReaction,\n activeEmojiInteractions,\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 } = getActions();\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 // eslint-disable-next-line no-null/no-null\n const contentRef = 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 {\n id: messageId, chatId, forwardInfo, viaBotId,\n } = 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 hasAnimatedEmoji = localSticker || animatedEmoji;\n const hasReactions = reactionMessage?.reactions && !areReactionsEmpty(reactionMessage.reactions);\n const asForwarded = (\n forwardInfo\n && (!isChatWithSelf || isScheduled)\n && !isRepliesChat\n && !forwardInfo.isLinkedChannelPost\n && !customShape\n );\n const isAlbum = Boolean(album) && album!.messages.length > 1;\n const isInDocumentGroupNotFirst = isInDocumentGroup && !isFirstInDocumentGroup;\n const isInDocumentGroupNotLast = isInDocumentGroup && !isLastInDocumentGroup;\n const isContextMenuShown = contextMenuPosition !== undefined;\n const canShowActionButton = (\n !(isContextMenuShown || isInSelectMode || isForwarding)\n && !isInDocumentGroupNotLast\n );\n const canForward = isChannel && !isScheduled;\n const canFocus = Boolean(isPinnedList\n || (forwardInfo\n && (forwardInfo.isChannelPost || (isChatWithSelf && !isOwn) || isRepliesChat)\n && forwardInfo.fromMessageId\n ));\n\n const withCommentButton = threadInfo && !isInDocumentGroupNotLast && messageListType === 'thread' && !noComments;\n const withQuickReactionButton = !IS_TOUCH_ENV && !isInSelectMode && defaultReaction && !isInDocumentGroupNotLast;\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 messageSender = canShowSender ? sender : undefined;\n\n const avatarPeer = forwardInfo && (isChatWithSelf || isRepliesChat || !messageSender) ? originSender : messageSender;\n const senderPeer = forwardInfo ? originSender : messageSender;\n\n const {\n handleMouseDown,\n handleClick,\n handleContextMenu,\n handleDoubleClick,\n handleContentDoubleClick,\n handleMouseMove,\n handleSendQuickReaction,\n handleMouseLeave,\n isSwiped,\n isQuickReactionVisible,\n handleDocumentGroupMouseEnter,\n } = useOuterHandlers(\n selectMessage,\n ref,\n messageId,\n isAlbum,\n Boolean(isInSelectMode),\n Boolean(canReply),\n Boolean(isProtected),\n onContextMenu,\n handleBeforeContextMenu,\n chatId,\n isContextMenuShown,\n contentRef,\n isOwn,\n isInDocumentGroupNotLast,\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 Boolean(activeReaction) && 'has-active-reaction',\n );\n\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, webPage, invoice, location,\n } = getMessageContent(message);\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 hasReactions,\n isGeoLiveActive: location?.type === 'geoLive' && !isGeoLiveExpired(message, getServerTime(serverTimeOffset)),\n });\n\n const withAppendix = contentClassName.includes('has-appendix');\n const textParts = renderMessageText(message, highlight, isEmojiOnlyMessage(customShape));\n\n let metaPosition!: MetaPosition;\n if (isInDocumentGroupNotLast) {\n metaPosition = 'none';\n } else if (textParts && !hasAnimatedEmoji && !webPage) {\n metaPosition = 'in-text';\n } else {\n metaPosition = 'standalone';\n }\n\n let reactionsPosition!: ReactionsPosition;\n if (areReactionsInMeta) {\n reactionsPosition = 'in-meta';\n } else if (hasReactions) {\n if (customShape || ((photo || video || hasAnimatedEmoji) && !textParts)) {\n reactionsPosition = 'outside';\n } else if (asForwarded) {\n metaPosition = 'standalone';\n reactionsPosition = 'inside';\n } else {\n reactionsPosition = 'inside';\n }\n } else {\n reactionsPosition = 'none';\n }\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 const signature = (isChannel && message.adminTitle) || (!asForwarded && forwardInfo?.adminTitle) || undefined;\n const metaSafeAuthorWidth = useMemo(() => {\n return signature ? calculateAuthorWidth(signature) : undefined;\n }, [signature]);\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 renderReactionsAndMeta() {\n const meta = (\n \n );\n\n if (reactionsPosition !== 'inside') {\n return meta;\n }\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 textContentClass = buildClassName(\n 'text-content',\n metaPosition === 'in-text' && '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 {localSticker && (\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 {!hasAnimatedEmoji && textParts && (\n

\n {textParts}\n {metaPosition === 'in-text' && renderReactionsAndMeta()}\n

\n )}\n\n {webPage && (\n \n )}\n {invoice && }\n {location && (\n \n )}\n
\n );\n }\n\n function renderSenderName() {\n const media = photo || video || location;\n const shouldRender = !(customShape && !viaBotId) && (\n (withSenderName && !media) || asForwarded || viaBotId || forceSenderName\n ) && !isInDocumentGroupNotFirst && !(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 && !isInDocumentGroupNotFirst && (\n
{lang('ForwardedMessage')}
\n )}\n {renderContent()}\n {!isInDocumentGroupNotLast && metaPosition === 'standalone' && renderReactionsAndMeta()}\n {canShowActionButton && canForward ? (\n \n \n \n ) : canShowActionButton && canFocus ? (\n \n \n \n ) : undefined}\n {withCommentButton && }\n {withAppendix && (\n
\n )}\n {withQuickReactionButton && (\n \n \n
\n )}\n \n {message.inlineButtons && (\n \n )}\n {reactionsPosition === 'outside' && (\n \n )}\n \n {contextMenuPosition && (\n \n )}\n \n );\n};\n\nexport default memo(withGlobal(\n (global, ownProps): StateProps => {\n const {\n focusedMessage, forwardMessages, lastSyncTime, serverTimeOffset,\n } = global;\n const {\n message, album, withSenderName, withAvatar, threadId, messageListType, isLastInDocumentGroup,\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 const isInDocumentGroup = Boolean(message.groupedId) && !message.isInAlbum;\n const documentGroupFirstMessageId = isInDocumentGroup\n ? selectMessageIdsByGroupId(global, chatId, message.groupedId!)![0]\n : undefined;\n const reactionMessage = isInDocumentGroup ? (\n isLastInDocumentGroup ? selectChatMessage(global, chatId, documentGroupFirstMessageId!) : undefined\n ) : message;\n\n const localSticker = singleEmoji ? selectLocalAnimatedEmoji(global, singleEmoji) : undefined;\n\n return {\n theme: selectTheme(global),\n chatUsername,\n forceSenderName,\n sender,\n canShowSender,\n originSender,\n botSender,\n shouldHideReply,\n isThreadTop,\n replyMessage,\n replyMessageSender,\n isInDocumentGroup,\n isProtected: selectIsMessageProtected(global, message),\n isFocused,\n isForwarding,\n reactionMessage,\n isChatWithSelf,\n isRepliesChat,\n isChannel,\n canReply,\n lastSyncTime,\n serverTimeOffset,\n highlight,\n isSingleEmoji: Boolean(singleEmoji),\n animatedEmoji: singleEmoji ? selectAnimatedEmoji(global, singleEmoji) : undefined,\n animatedEmojiEffect: singleEmoji && isUserId(chatId) ? selectAnimatedEmojiEffect(global, singleEmoji) : undefined,\n animatedEmojiSoundId: singleEmoji ? selectAnimatedEmojiSound(global, singleEmoji) : undefined,\n localSticker,\n localEffect: localSticker && isUserId(chatId) ? selectLocalAnimatedEmojiEffect(localSticker) : undefined,\n isInSelectMode: selectIsInSelectMode(global),\n isSelected,\n isGroupSelected: (\n Boolean(message.groupedId)\n && !message.isInAlbum\n && 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 availableReactions: global.availableReactions,\n defaultReaction: isMessageLocal(message) ? undefined : selectDefaultReaction(global, chatId),\n activeReaction: reactionMessage && global.activeReactions[reactionMessage.id],\n activeEmojiInteractions: global.activeEmojiInteractions,\n ...(isOutgoing && { outgoingStatus: selectOutgoingStatus(global, message, messageListType === 'scheduled') }),\n ...(typeof uploadProgress === 'number' && { uploadProgress }),\n ...(isFocused && { focusDirection, noFocusHighlight, isResizingContainer }),\n };\n },\n)(Message));\n","import React, { useCallback } from '../../../../lib/teact/teact';\nimport { getActions } from '../../../../global';\n\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 openChat, showNotification, focusMessage, openMediaViewer, openAudioPlayer,\n markMessagesRead, cancelSendingMessage, sendPollVote, openForwardMenu, focusMessageInComments,\n } = getActions();\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 openChat({ id: avatarPeer.id });\n }, [avatarPeer, 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 {\n openChat({ id: senderPeer.id });\n }\n }, [\n asForwarded, focusMessage, forwardInfo, lang, openChat, senderPeer, showNotification,\n ]);\n\n const handleViaBotClick = useCallback(() => {\n if (!botSender) {\n return;\n }\n\n openChat({ id: botSender.id });\n }, [botSender, openChat]);\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 { getActions, withGlobal } from '../../../global';\n\nimport { ApiChat, ApiSponsoredMessage, ApiUser } from '../../../api/types';\n\nimport { renderTextWithEntities } from '../../common/helpers/renderTextWithEntities';\nimport { selectChat, selectSponsoredMessage, selectUser } from '../../../global/selectors';\nimport { getChatTitle, getUserFullName } from '../../../global/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 } = getActions();\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 {\n getMessageHtmlId, getMessageOriginalId, isActionMessage, isOwnMessage,\n} from '../../global/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 { getActions } from '../../global';\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 areReactionsInMeta: 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 areReactionsInMeta,\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 } = getActions();\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 === getMessageHtmlId(message.previousLocalId)) {\n anchorIdRef.current = getMessageHtmlId(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 { getActions } from '../../../global';\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 } = getActions();\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 if (!containerRef.current) {\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 { getActions, withGlobal } from '../../global';\n\nimport { ApiSticker, ApiUpdateConnectionStateType } from '../../api/types';\n\nimport { selectChat } from '../../global/selectors';\nimport { useIntersectionObserver } from '../../hooks/useIntersectionObserver';\nimport useLang from '../../hooks/useLang';\nimport { getUserIdDividend } from '../../global/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 } = getActions();\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 { getActions, getGlobal, withGlobal } from '../../global';\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 '../../global/selectors';\nimport {\n isChatChannel,\n isUserId,\n isChatWithRepliesBot,\n isChatGroup,\n} from '../../global/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';\nimport useInterval from '../../hooks/useInterval';\nimport useNativeCopySelectedMessages from '../../hooks/useNativeCopySelectedMessages';\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 MESSAGE_REACTIONS_POLLING_INTERVAL = 15 * 1000;\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 {\n loadViewportMessages, setScrollOffset, loadSponsoredMessages, loadMessageReactions, copyMessagesByIds,\n } = getActions();\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 useNativeCopySelectedMessages(copyMessagesByIds);\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 useInterval(() => {\n if (!messageIds || !messagesById) {\n return;\n }\n const ids = messageIds.filter((l) => messagesById[l]?.reactions);\n\n if (!ids.length) return;\n\n loadMessageReactions({ chatId, ids });\n }, MESSAGE_REACTIONS_POLLING_INTERVAL);\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 containerRef.current!.dataset.normalHeight = String(containerRef.current!.offsetHeight);\n }, [windowHeight, 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 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] as const);\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 { useEffect } from '../lib/teact/teact';\nimport { IS_MAC_OS } from '../util/environment';\nimport getKeyFromEvent from '../util/getKeyFromEvent';\nimport getMessageIdsForSelectedText from '../util/getMessageIdsForSelectedText';\n\nconst useNativeCopySelectedMessages = (copyMessagesByIds: ({ messageIds }: { messageIds?: number[] }) => void) => {\n useEffect(() => {\n function handleCopy(e: KeyboardEvent) {\n if (((IS_MAC_OS && e.metaKey) || (!IS_MAC_OS && e.ctrlKey)) && getKeyFromEvent(e) === 'c') {\n const messageIds = getMessageIdsForSelectedText();\n\n if (messageIds && messageIds.length > 0) {\n e.preventDefault();\n copyMessagesByIds({ messageIds });\n }\n }\n }\n\n document.addEventListener('keydown', handleCopy, false);\n\n return () => {\n document.removeEventListener('keydown', handleCopy, false);\n };\n }, [copyMessagesByIds]);\n};\n\nexport default useNativeCopySelectedMessages;\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, true);\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 { getActions, withGlobal } from '../../global';\n\nimport { MessageListType } from '../../global/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\n\nimport { selectChat, selectCurrentMessageList } from '../../global/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 } = getActions();\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","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","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 { IOpusRecorder } from 'opus-recorder';\n\nexport type Result = { blob: Blob; duration: number; waveform: number[] };\n\nconst encoderPath = new URL('opus-recorder/dist/encoderWorker.min', import.meta.url).href;\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 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","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';\nimport getFilesFromDataTransferItems from '../helpers/getFilesFromDataTransferItems';\n\nconst CLIPBOARD_ACCEPTED_TYPES = ['image/png', 'image/jpeg', 'image/gif'];\nconst MAX_MESSAGE_LENGTH = 4096;\n\nconst useClipboardPaste = (\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 pastedText = e.clipboardData.getData('text').substring(0, MAX_MESSAGE_LENGTH);\n const { items } = e.clipboardData;\n let files: File[] = [];\n\n e.preventDefault();\n if (items.length > 0) {\n files = await getFilesFromDataTransferItems(items);\n }\n\n if (files.length === 0 && !pastedText) {\n return;\n }\n\n if (files.length > 0 && !editedMessage) {\n const newAttachments = await Promise.all(files.map((file) => {\n return buildAttachment(file.name, file, files.length === 1 && CLIPBOARD_ACCEPTED_TYPES.includes(file.type));\n }));\n setAttachments((attachments) => attachments.concat(newAttachments));\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\nexport default useClipboardPaste;\n","import { useCallback, useEffect, useMemo } from '../../../../lib/teact/teact';\nimport { getActions } from '../../../../global';\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 useBackgroundMode from '../../../../hooks/useBackgroundMode';\nimport useBeforeUnload from '../../../../hooks/useBeforeUnload';\nimport { IS_TOUCH_ENV } from '../../../../util/environment';\nimport { getTextWithEntitiesAsHtml } from '../../../common/helpers/renderTextWithEntities';\n\n// Used to avoid running debounced callbacks when chat changes.\nlet currentChatId: string | undefined;\nlet currentThreadId: number | undefined;\n\nconst useDraft = (\n draft: ApiFormattedText | undefined,\n chatId: string,\n threadId: number,\n htmlRef: { current: string },\n setHtml: (html: string) => void,\n editedMessage: ApiMessage | undefined,\n) => {\n const { saveDraft, clearDraft } = getActions();\n\n const updateDraft = useCallback((draftChatId: string, draftThreadId: number) => {\n const currentHtml = htmlRef.current;\n if (editedMessage) return;\n if (currentHtml.length) {\n saveDraft({ chatId: draftChatId, threadId: draftThreadId, draft: parseMessageInput(currentHtml!) });\n } else if (currentHtml !== undefined) {\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 (editedMessage || !draft) {\n return;\n }\n\n setHtml(getTextWithEntitiesAsHtml(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, editedMessage]);\n\n const html = htmlRef.current;\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\nexport default useDraft;\n","import { useState } from '../lib/teact/teact';\n\nimport useDebounce from './useDebounce';\nimport useOnChange from './useOnChange';\nimport useHeavyAnimationCheck from './useHeavyAnimationCheck';\nimport useFlag from './useFlag';\n\nexport default function useDebouncedMemo(\n resolverFn: () => R, ms: number, dependencies: D,\n): R | undefined {\n const runDebounced = useDebounce(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 runDebounced(() => {\n setValue(resolverFn());\n });\n }, [...dependencies, isFrozen]);\n\n return value;\n}\n","import { useCallback, useEffect } from '../../../../lib/teact/teact';\nimport { getActions } from '../../../../global';\nimport { InlineBotSettings } from '../../../../types';\nimport useFlag from '../../../../hooks/useFlag';\nimport usePrevious from '../../../../hooks/usePrevious';\nimport useDebouncedMemo from '../../../../hooks/useDebouncedMemo';\n\nconst DEBOUNCE_MS = 300;\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;\nconst MEMO_NO_RESULT = {\n username: '',\n query: '',\n canShowHelp: false,\n usernameLowered: '',\n};\n\nconst tempEl = document.createElement('div');\n\nexport default function useInlineBotTooltip(\n isAllowed: boolean,\n chatId: string,\n html: string,\n inlineBots?: Record,\n) {\n const { queryInlineBot, resetInlineBot } = getActions();\n\n const [isOpen, markIsOpen, unmarkIsOpen] = useFlag();\n const {\n username, query, canShowHelp, usernameLowered,\n } = useDebouncedMemo(() => parseBotQuery(html), DEBOUNCE_MS, [html]) || {};\n const prevQuery = usePrevious(query);\n const prevUsername = usePrevious(username);\n const inlineBotData = usernameLowered ? inlineBots?.[usernameLowered] : undefined;\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 id: botId,\n isGallery,\n switchPm,\n results,\n closeTooltip: unmarkIsOpen,\n help: canShowHelp && help ? `@${username} ${help}` : undefined,\n loadMore,\n };\n}\n\nfunction parseBotQuery(html: string) {\n const text = getPlainText(html);\n const result = text.match(INLINE_BOT_QUERY_REGEXP);\n if (!result) {\n return MEMO_NO_RESULT;\n }\n\n return {\n username: result[1],\n query: result[2],\n canShowHelp: result[2] === '' && !text.match(HAS_NEW_LINE),\n usernameLowered: result[1].toLowerCase(),\n };\n}\n\nfunction getPlainText(html: string) {\n tempEl.innerHTML = html.replace(/
/g, '\\n');\n\n return tempEl.innerText;\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 setFilteredBotCommands(undefined);\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 setFilteredBotCommands(undefined);\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, {\n FC, memo, useCallback, useEffect,\n} from '../../../lib/teact/teact';\n\nimport { CONTENT_TYPES_WITH_PREVIEW } from '../../../config';\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { openSystemFilesDialog } from '../../../util/systemFilesDialog';\nimport useMouseInside from '../../../hooks/useMouseInside';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\n\nimport ResponsiveHoverButton from '../../ui/ResponsiveHoverButton';\nimport Menu from '../../ui/Menu';\nimport MenuItem from '../../ui/MenuItem';\n\nimport './AttachMenu.scss';\n\nexport type OwnProps = {\n isButtonVisible: boolean;\n canAttachMedia: boolean;\n canAttachPolls: boolean;\n onFileSelect: (files: File[], isQuick: boolean) => void;\n onPollCreate: () => void;\n};\n\nconst AttachMenu: FC = ({\n isButtonVisible, canAttachMedia, canAttachPolls, onFileSelect, onPollCreate,\n}) => {\n const [isAttachMenuOpen, openAttachMenu, closeAttachMenu] = useFlag();\n const [handleMouseEnter, handleMouseLeave, markMouseInside] = useMouseInside(isAttachMenuOpen, closeAttachMenu);\n\n useEffect(() => {\n if (isAttachMenuOpen) {\n markMouseInside();\n }\n }, [isAttachMenuOpen, markMouseInside]);\n\n const handleFileSelect = useCallback((e: Event, isQuick: boolean) => {\n const { files } = e.target as HTMLInputElement;\n\n if (files && files.length > 0) {\n onFileSelect(Array.from(files), isQuick);\n }\n }, [onFileSelect]);\n\n const handleQuickSelect = useCallback(() => {\n openSystemFilesDialog(\n Array.from(CONTENT_TYPES_WITH_PREVIEW).join(','),\n (e) => handleFileSelect(e, true),\n );\n }, [handleFileSelect]);\n\n const handleDocumentSelect = useCallback(() => {\n openSystemFilesDialog('*', (e) => handleFileSelect(e, false));\n }, [handleFileSelect]);\n\n const lang = useLang();\n\n if (!isButtonVisible) {\n return undefined;\n }\n\n return (\n
\n \n \n \n \n {/*\n ** Using ternary operator here causes some attributes from first clause\n ** transferring to the fragment content in the second clause\n */}\n {!canAttachMedia && (\n Posting media content is not allowed in this group.\n )}\n {canAttachMedia && (\n <>\n \n {lang('AttachmentMenu.PhotoOrVideo')}\n \n {lang('AttachDocument')}\n \n )}\n {canAttachPolls && (\n {lang('Poll')}\n )}\n \n
\n );\n};\n\nexport default memo(AttachMenu);\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 './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 memo(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 { getActions, withGlobal } from '../../../global';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { selectChatMessage, selectCurrentMessageList } from '../../../global/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 } = getActions();\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?.keyboardButtons]);\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 { getActions, withGlobal } from '../../../global';\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 '../../../global/selectors';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport buildClassName from '../../../util/buildClassName';\nimport { isUserId } from '../../../global/helpers';\n\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport useShowTransition from '../../../hooks/useShowTransition';\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\ntype OwnProps = {\n onClear?: () => void;\n};\n\nconst FORWARD_RENDERING_DELAY = 300;\n\nconst ComposerEmbeddedMessage: FC = ({\n replyingToId,\n editingId,\n message,\n sender,\n shouldAnimate,\n forwardedMessagesCount,\n onClear,\n}) => {\n const {\n setReplyingToId,\n setEditingId,\n focusMessage,\n exitForwardMode,\n } = getActions();\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 onClear?.();\n }, [replyingToId, editingId, forwardedMessagesCount, onClear, 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, { FC, memo, useEffect } from '../../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../../global';\n\nimport { ApiMessage, ApiMessageEntityTypes, ApiWebPage } from '../../../api/types';\nimport { ISettings } from '../../../types';\n\nimport { RE_LINK_TEMPLATE } from '../../../config';\nimport { selectNoWebPage, selectTheme } from '../../../global/selectors';\nimport parseMessageInput from '../../../util/parseMessageInput';\nimport useOnChange from '../../../hooks/useOnChange';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useCurrentOrPrev from '../../../hooks/useCurrentOrPrev';\nimport useDebouncedMemo from '../../../hooks/useDebouncedMemo';\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 DEBOUNCE_MS = 300;\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 } = getActions();\n\n const link = useDebouncedMemo(() => {\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 }, DEBOUNCE_MS, [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 './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 { getActions, getGlobal, withGlobal } from '../../../global';\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, SEND_MESSAGE_ACTION_INTERVAL,\n} from '../../../config';\nimport { IS_VOICE_RECORDING_SUPPORTED, IS_SINGLE_COLUMN_LAYOUT, IS_IOS } from '../../../util/environment';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport {\n selectChat,\n selectIsRightColumnShown,\n selectIsInSelectMode,\n selectNewestMessageWithBotKeyboardButtons,\n selectDraft,\n selectScheduledIds,\n selectEditingMessage,\n selectIsChatWithSelf,\n selectChatBot,\n selectChatMessage,\n selectUser,\n selectCanScheduleUntilOnline,\n selectEditingScheduledDraft,\n selectEditingDraft,\n} from '../../../global/selectors';\nimport {\n getAllowedAttachmentOptions,\n getChatSlowModeOptions,\n isChatAdmin,\n isChatSuperGroup,\n isChatChannel,\n} from '../../../global/helpers';\nimport { formatMediaDuration, formatVoiceRecordDuration } 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 { useStateRef } from '../../../hooks/useStateRef';\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';\nimport useSchedule from '../../../hooks/useSchedule';\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';\nimport Avatar from '../../common/Avatar';\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 SendAsMenu from './SendAsMenu.async';\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 isChannel?: 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 recentEmojis: string[];\n lastSyncTime?: number;\n contentToBeScheduled?: GlobalState['messages']['contentToBeScheduled'];\n shouldSuggestStickers?: boolean;\n baseEmojiKeywords?: Record;\n emojiKeywords?: Record;\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 editingDraft?: ApiFormattedText;\n }\n & Pick;\n\nenum MainButtonState {\n Send = 'send',\n Record = 'record',\n Edit = 'edit',\n Schedule = 'schedule',\n}\n\ntype ScheduledMessageArgs = GlobalState['messages']['contentToBeScheduled'] | {\n id: string; queryId: string; isSilent?: boolean;\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 isChannel,\n isRightColumnShown,\n isSelectModeActive,\n isForwarding,\n isPollModalOpen,\n botKeyboardMessageId,\n botKeyboardPlaceholder,\n withScheduledButton,\n stickersForEmoji,\n groupChatMembers,\n topInlineBotIds,\n currentUserId,\n lastSyncTime,\n contentToBeScheduled,\n shouldSuggestStickers,\n baseEmojiKeywords,\n emojiKeywords,\n recentEmojis,\n inlineBots,\n isInlineBotLoading,\n botCommands,\n chatBotCommands,\n sendAsUser,\n sendAsChat,\n sendAsId,\n editingDraft,\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 loadFullChat,\n } = getActions();\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 htmlRef = useStateRef(html);\n const lastMessageSendTimeSeconds = useRef();\n const prevDropAreaState = usePrevious(dropAreaState);\n const { width: windowWidth } = windowSize.get();\n const sendAsIds = chat?.sendAsIds;\n const canShowSendAs = sendAsIds && (sendAsIds.length > 1 || !sendAsIds.includes(currentUserId!));\n // Prevent Symbol Menu from closing when calendar is open\n const [isSymbolMenuForced, forceShowSymbolMenu, cancelForceShowSymbolMenu] = useFlag();\n const sendMessageAction = useSendMessageAction(chatId, threadId);\n\n const handleScheduleCancel = useCallback(() => {\n cancelForceShowSymbolMenu();\n }, [cancelForceShowSymbolMenu]);\n const [requestCalendar, calendar] = useSchedule(canScheduleUntilOnline, handleScheduleCancel);\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 useEffect(() => {\n if (chatId && chat && lastSyncTime && !chat.fullInfo && isReady && isChatSuperGroup(chat)) {\n loadFullChat({ chatId });\n }\n }, [chat, chatId, isReady, lastSyncTime, loadFullChat]);\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 const [attachments, setAttachments] = useState([]);\n\n const [isBotKeyboardOpen, openBotKeyboard, closeBotKeyboard] = useFlag();\n const [isBotCommandMenuOpen, openBotCommandMenu, closeBotCommandMenu] = 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 ? MainButtonState.Edit\n : (!IS_VOICE_RECORDING_SUPPORTED || activeVoiceRecording || (html && !attachments.length) || isForwarding)\n ? (shouldSchedule ? MainButtonState.Schedule : MainButtonState.Send)\n : MainButtonState.Record;\n const canShowCustomSendMenu = !shouldSchedule;\n\n const {\n isMentionTooltipOpen, closeMentionTooltip, insertMention, mentionFilteredUsers,\n } = useMentionTooltip(\n !attachments.length,\n htmlRef,\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 {\n canSendStickers, canSendGifs, canAttachMedia, canAttachPolls, canAttachEmbedLinks,\n } = useMemo(() => getAllowedAttachmentOptions(chat, isChatWithBot), [chat, isChatWithBot]);\n\n const isAdmin = chat && isChatAdmin(chat);\n const slowMode = getChatSlowModeOptions(chat);\n\n const { isStickerTooltipOpen, closeStickerTooltip } = useStickerTooltip(\n Boolean(shouldSuggestStickers && canSendStickers && !attachments.length),\n html,\n stickersForEmoji,\n !isReady,\n );\n const {\n isEmojiTooltipOpen, closeEmojiTooltip, filteredEmojis, insertEmoji,\n } = useEmojiTooltip(\n Boolean(shouldSuggestStickers && canSendStickers && !attachments.length),\n htmlRef,\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 }, [htmlRef]);\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 }, [htmlRef]);\n\n const resetComposer = useCallback((shouldPreserveInput = false) => {\n if (!shouldPreserveInput) {\n setHtml('');\n }\n setAttachments(MEMO_EMPTY_ARRAY);\n closeStickerTooltip();\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, 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, handleEditCancel] = useEditing(\n htmlRef,\n setHtml,\n editingMessage,\n resetComposer,\n openDeleteModal,\n chatId,\n threadId,\n messageListType,\n draft,\n editingDraft,\n );\n useDraft(draft, chatId, threadId, htmlRef, setHtml, editingMessage);\n useClipboardPaste(insertTextAndUpdateCursor, setAttachments, editingMessage);\n\n const handleEmbeddedClear = useCallback(() => {\n if (editingMessage) {\n handleEditCancel();\n }\n }, [editingMessage, handleEditCancel]);\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(MEMO_EMPTY_ARRAY);\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 // No need to subscribe on updates in `mapStateToProps`\n const { serverTimeOffset } = getGlobal();\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,\n resetComposer, stopRecordingVoice, showDialog, slowMode, isAdmin, sendMessage, forwardMessages, lang, htmlRef,\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 handleMessageSchedule = useCallback((\n args: ScheduledMessageArgs, scheduledAt: number,\n ) => {\n if (args && 'queryId' in args) {\n const { id, queryId, isSilent } = args;\n sendInlineBotResult({\n id,\n queryId,\n scheduledAt,\n isSilent,\n });\n return;\n }\n\n const { isSilent, ...restArgs } = args || {};\n\n if (!args || Object.keys(restArgs).length === 0) {\n void handleSend(Boolean(isSilent), scheduledAt);\n } else {\n sendMessage({\n ...args,\n scheduledAt,\n });\n }\n }, [handleSend, sendInlineBotResult, sendMessage]);\n\n useEffect(() => {\n if (contentToBeScheduled) {\n requestCalendar((scheduledAt) => {\n handleMessageSchedule(contentToBeScheduled, scheduledAt);\n });\n }\n }, [contentToBeScheduled, handleMessageSchedule, requestCalendar]);\n\n const handleStickerSelect = useCallback((\n sticker: ApiSticker, isSilent?: boolean, isScheduleRequested?: boolean, shouldPreserveInput = false,\n ) => {\n sticker = {\n ...sticker,\n isPreloadedGlobally: true,\n };\n\n if (shouldSchedule || isScheduleRequested) {\n forceShowSymbolMenu();\n requestCalendar((scheduledAt) => {\n cancelForceShowSymbolMenu();\n handleMessageSchedule({ sticker, isSilent }, scheduledAt);\n requestAnimationFrame(() => {\n resetComposer(shouldPreserveInput);\n });\n });\n } else {\n sendMessage({ sticker, isSilent });\n requestAnimationFrame(() => {\n resetComposer(shouldPreserveInput);\n });\n }\n }, [\n shouldSchedule, forceShowSymbolMenu, requestCalendar, cancelForceShowSymbolMenu, handleMessageSchedule,\n resetComposer, sendMessage,\n ]);\n\n const handleGifSelect = useCallback((gif: ApiVideo, isSilent?: boolean, isScheduleRequested?: boolean) => {\n if (shouldSchedule || isScheduleRequested) {\n forceShowSymbolMenu();\n requestCalendar((scheduledAt) => {\n cancelForceShowSymbolMenu();\n handleMessageSchedule({ gif, isSilent }, scheduledAt);\n requestAnimationFrame(() => {\n resetComposer(true);\n });\n });\n } else {\n sendMessage({ gif, isSilent });\n requestAnimationFrame(() => {\n resetComposer(true);\n });\n }\n }, [\n shouldSchedule, forceShowSymbolMenu, requestCalendar, cancelForceShowSymbolMenu, handleMessageSchedule,\n resetComposer, sendMessage,\n ]);\n\n const handleInlineBotSelect = useCallback((\n inlineResult: ApiBotInlineResult | ApiBotInlineMediaResult, isSilent?: boolean, isScheduleRequested?: boolean,\n ) => {\n if (connectionState !== 'connectionStateReady') {\n return;\n }\n\n if (shouldSchedule || isScheduleRequested) {\n requestCalendar((scheduledAt) => {\n handleMessageSchedule({\n id: inlineResult.id,\n queryId: inlineResult.queryId,\n isSilent,\n }, scheduledAt);\n });\n } else {\n sendInlineBotResult({\n id: inlineResult.id,\n queryId: inlineResult.queryId,\n isSilent,\n });\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 }, [\n chatId, clearDraft, connectionState, handleMessageSchedule, requestCalendar, resetComposer, sendInlineBotResult,\n shouldSchedule,\n ]);\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 requestCalendar((scheduledAt) => {\n handleMessageSchedule({ poll }, scheduledAt);\n });\n closePollModal();\n } else {\n sendMessage({ poll });\n closePollModal();\n }\n }, [closePollModal, handleMessageSchedule, requestCalendar, sendMessage, shouldSchedule]);\n\n const handleSendSilent = useCallback(() => {\n if (shouldSchedule) {\n requestCalendar((scheduledAt) => {\n handleMessageSchedule({ isSilent: true }, scheduledAt);\n });\n } else {\n void handleSend(true);\n }\n }, [handleMessageSchedule, handleSend, requestCalendar, shouldSchedule]);\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 handleSend();\n break;\n case MainButtonState.Record:\n void startRecordingVoice();\n break;\n case MainButtonState.Edit:\n handleEditComplete();\n break;\n case MainButtonState.Schedule:\n if (activeVoiceRecording) {\n pauseRecordingVoice();\n }\n requestCalendar((scheduledAt) => {\n handleMessageSchedule({}, scheduledAt);\n });\n break;\n default:\n break;\n }\n }, [\n mainButtonState, handleSend, startRecordingVoice, handleEditComplete, activeVoiceRecording, requestCalendar,\n pauseRecordingVoice, handleMessageSchedule,\n ]);\n\n const areVoiceMessagesNotAllowed = mainButtonState === MainButtonState.Record && !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 handleSendScheduled = useCallback(() => {\n requestCalendar((scheduledAt) => {\n handleMessageSchedule({}, scheduledAt);\n });\n }, [handleMessageSchedule, requestCalendar]);\n\n const onSend = mainButtonState === MainButtonState.Edit\n ? handleEditComplete\n : mainButtonState === MainButtonState.Schedule ? handleSendScheduled\n : handleSend;\n\n return (\n
\n {canAttachMedia && isReady && (\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 {canShowSendAs && (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 && 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 \n {canShowCustomSendMenu && (\n \n )}\n {calendar}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const chat = selectChat(global, chatId);\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 { currentUserId } = global;\n const defaultSendAsId = chat?.fullInfo ? chat?.fullInfo?.sendAsId || currentUserId : undefined;\n const sendAsId = chat?.sendAsIds && defaultSendAsId && chat.sendAsIds.includes(defaultSendAsId)\n ? defaultSendAsId\n : (chat?.adminRights?.anonymous ? chat?.id : undefined);\n const sendAsUser = sendAsId ? selectUser(global, sendAsId) : undefined;\n const sendAsChat = !sendAsUser && sendAsId ? selectChat(global, sendAsId) : undefined;\n\n const editingDraft = messageListType === 'scheduled'\n ? selectEditingScheduledDraft(global, chatId)\n : selectEditingDraft(global, chatId, threadId);\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: selectCanScheduleUntilOnline(global, chatId),\n isChannel: chat ? isChatChannel(chat) : undefined,\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 lastSyncTime: global.lastSyncTime,\n contentToBeScheduled: global.messages.contentToBeScheduled,\n shouldSuggestStickers,\n recentEmojis: global.recentEmojis,\n baseEmojiKeywords: baseEmojiKeywords?.keywords,\n emojiKeywords: emojiKeywords?.keywords,\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 editingDraft,\n };\n },\n)(Composer));\n","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\nconst useVoiceRecording = () => {\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\nexport default useVoiceRecording;\n","import { useEffect, useMemo } from '../../../../lib/teact/teact';\nimport { getActions } from '../../../../global';\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 } = getActions();\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 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 { getActions } from '../../../../global';\n\nimport { ApiFormattedText, ApiMessage } from '../../../../api/types';\nimport { MessageListType } from '../../../../global/types';\n\nimport useEffectWithPrevDeps from '../../../../hooks/useEffectWithPrevDeps';\nimport { EDITABLE_INPUT_ID } from '../../../../config';\nimport parseMessageInput from '../../../../util/parseMessageInput';\nimport focusEditableElement from '../../../../util/focusEditableElement';\nimport { hasMessageMedia } from '../../../../global/helpers';\nimport { getTextWithEntitiesAsHtml } from '../../../common/helpers/renderTextWithEntities';\nimport { fastRaf } from '../../../../util/schedulers';\nimport useBackgroundMode from '../../../../hooks/useBackgroundMode';\nimport useBeforeUnload from '../../../../hooks/useBeforeUnload';\n\nconst useEditing = (\n htmlRef: { current: string },\n setHtml: (html: string) => void,\n editedMessage: ApiMessage | undefined,\n resetComposer: (shouldPreserveInput?: boolean) => void,\n openDeleteModal: () => void,\n chatId: string,\n threadId: number,\n type: MessageListType,\n draft?: ApiFormattedText,\n editingDraft?: ApiFormattedText,\n) => {\n const { editMessage, setEditingDraft } = getActions();\n\n useEffectWithPrevDeps(([prevEditedMessage]) => {\n if (!editedMessage) {\n return;\n }\n if (prevEditedMessage?.id === editedMessage.id) {\n return;\n }\n\n const html = getTextWithEntitiesAsHtml(editingDraft?.text.length ? editingDraft : editedMessage.content.text);\n setHtml(html);\n // `fastRaf` would execute syncronously in this case\n requestAnimationFrame(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n focusEditableElement(messageInput, true);\n });\n }, [editedMessage, setHtml] as const);\n\n useEffect(() => {\n if (!editedMessage) return undefined;\n return () => {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const edited = parseMessageInput(htmlRef.current!);\n const update = edited.text.length ? edited : undefined;\n setEditingDraft({\n chatId, threadId, type, text: update,\n });\n };\n }, [chatId, editedMessage, htmlRef, setEditingDraft, threadId, type]);\n\n const restoreNewDraftAfterEditing = useCallback(() => {\n if (!draft) return;\n // Run 1 frame after editing draft reset\n fastRaf(() => {\n setHtml(getTextWithEntitiesAsHtml(draft));\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n requestAnimationFrame(() => {\n focusEditableElement(messageInput, true);\n });\n });\n }, [draft, setHtml]);\n\n const handleEditCancel = useCallback(() => {\n resetComposer();\n restoreNewDraftAfterEditing();\n }, [resetComposer, restoreNewDraftAfterEditing]);\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 restoreNewDraftAfterEditing();\n }, [editMessage, editedMessage, htmlRef, openDeleteModal, resetComposer, restoreNewDraftAfterEditing]);\n\n const handleBlur = useCallback(() => {\n if (!editedMessage) return;\n const edited = parseMessageInput(htmlRef.current!);\n const update = edited.text.length ? edited : undefined;\n setEditingDraft({\n chatId, threadId, type, text: update,\n });\n }, [chatId, editedMessage, htmlRef, setEditingDraft, threadId, type]);\n\n useBackgroundMode(handleBlur);\n useBeforeUnload(handleBlur);\n\n return [handleEditComplete, handleEditCancel];\n};\n\nexport default useEditing;\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, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './EmojiInteractionAnimation';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst EmojiInteractionAnimationAsync: FC = (props) => {\n const { activeEmojiInteraction } = props;\n const EmojiInteractionAnimation = useModuleLoader(\n Bundles.Extra, 'EmojiInteractionAnimation', !activeEmojiInteraction,\n );\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return EmojiInteractionAnimation ? : undefined;\n};\n\nexport default memo(EmojiInteractionAnimationAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './ReactorListModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst ReactorListModalAsync: FC = (props) => {\n const { isOpen } = props;\n const ReactorListModal = useModuleLoader(Bundles.Extra, 'ReactorListModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ReactorListModal ? : undefined;\n};\n\nexport default memo(ReactorListModalAsync);\n","import React, {\n FC, useEffect, useState, memo, useMemo, useCallback,\n} from '../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../global';\n\nimport { ApiChatBannedRights, MAIN_THREAD_ID } from '../../api/types';\nimport {\n MessageListType,\n MessageList as GlobalMessageList,\n ActiveEmojiInteraction,\n} 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 '../../global/selectors';\nimport {\n getCanPostInChat, getMessageSendingRestrictionReason, isChatChannel, isChatSuperGroup, isUserId,\n} from '../../global/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';\nimport EmojiInteractionAnimation from './EmojiInteractionAnimation.async';\nimport ReactorListModal from './ReactorListModal.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 isReactorListModalOpen: boolean;\n animationLevel?: number;\n shouldSkipHistoryAnimations?: boolean;\n currentTransitionKey: number;\n messageLists?: GlobalMessageList[];\n isChannel?: boolean;\n areChatSettingsLoaded?: boolean;\n canSubscribe?: boolean;\n canStartBot?: boolean;\n canRestartBot?: boolean;\n activeEmojiInteractions?: ActiveEmojiInteraction[];\n lastSyncTime?: number;\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 isReactorListModalOpen,\n animationLevel,\n shouldSkipHistoryAnimations,\n currentTransitionKey,\n isChannel,\n areChatSettingsLoaded,\n canSubscribe,\n canStartBot,\n canRestartBot,\n activeEmojiInteractions,\n lastSyncTime,\n}) => {\n const {\n openChat,\n unpinAllMessages,\n loadUser,\n loadChatSettings,\n closeLocalTextSearch,\n exitMessageSelectMode,\n closePaymentModal,\n clearReceipt,\n joinChannel,\n sendBotCommand,\n restartBot,\n } = getActions();\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 !shouldSkipHistoryAnimations && animationLevel !== ANIMATION_LEVEL_MIN,\n currentTransitionKey,\n prevTransitionKey,\n 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 useEffect(() => {\n if (!areChatSettingsLoaded && lastSyncTime) {\n loadChatSettings({ chatId });\n }\n }, [chatId, isPrivate, areChatSettingsLoaded, lastSyncTime, loadChatSettings]);\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 && items.length > 0 && 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,\n undefined,\n undefined,\n undefined,\n messageLists?.map(createMessageHash) || [],\n );\n\n useHistoryBack(isMobileSearchActive, closeLocalTextSearch);\n useHistoryBack(isSelectModeActive, exitMessageSelectMode);\n\n const isMessagingDisabled = Boolean(\n !isPinnedMessageList && !renderingCanPost && !renderingCanRestartBot && !renderingCanStartBot\n && !renderingCanSubscribe && messageSendingRestrictionReason,\n );\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 {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 {IS_SINGLE_COLUMN_LAYOUT && }\n \n )}\n {chatId && (\n \n )}\n
\n {activeEmojiInteractions?.map((activeEmojiInteraction, i) => (\n \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 {\n isLeftColumnShown, chats: { listIds }, activeEmojiInteractions, lastSyncTime,\n } = 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 isReactorListModalOpen: Boolean(global.reactorModal),\n animationLevel: global.settings.byKey.animationLevel,\n currentTransitionKey: Math.max(0, global.messages.messageLists.length - 1),\n activeEmojiInteractions,\n lastSyncTime,\n };\n\n if (!currentMessageList || !listIds.active) {\n return state;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const isPrivate = isUserId(chatId);\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,\n areChatSettingsLoaded: Boolean(chat?.settings),\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 withAnimations?: boolean,\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 (withAnimations) {\n setIsReady(false);\n } else {\n forceUpdate();\n }\n }\n\n useOnChange(() => {\n if (!withAnimations) {\n setIsReady(true);\n }\n }, [withAnimations]);\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: withAnimations ? handleOpenEnd : undefined,\n handleSlideStop: withAnimations ? handleSlideStop : undefined,\n };\n}\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../global';\n\nimport { ManagementScreens, ProfileState } from '../../types';\nimport { ApiExportedInvite } from '../../api/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 '../../global/selectors';\nimport {\n getCanAddContact, isChatAdmin, isChatChannel, isUserId,\n} from '../../global/helpers';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport useLang from '../../hooks/useLang';\nimport useFlag from '../../hooks/useFlag';\nimport { getDayStartAt } from '../../util/dateFormat';\n\nimport SearchInput from '../ui/SearchInput';\nimport Button from '../ui/Button';\nimport Transition from '../ui/Transition';\nimport ConfirmDialog from '../ui/ConfirmDialog';\n\nimport './RightHeader.scss';\n\ntype OwnProps = {\n chatId?: string;\n isColumnOpen?: boolean;\n isProfile?: boolean;\n isSearch?: boolean;\n isManagement?: boolean;\n isStatistics?: 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 onScreenSelect: (screen: ManagementScreens) => void;\n};\n\ntype StateProps = {\n canAddContact?: boolean;\n canManage?: boolean;\n canViewStatistics?: boolean;\n isChannel?: boolean;\n userId?: string;\n messageSearchQuery?: string;\n stickerSearchQuery?: string;\n gifSearchQuery?: string;\n isEditingInvite?: boolean;\n currentInviteInfo?: ApiExportedInvite;\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 Statistics,\n Management,\n ManageInitial,\n ManageChannelSubscribers,\n ManageChatAdministrators,\n ManageChatPrivacyType,\n ManageDiscussion,\n ManageGroupPermissions,\n ManageGroupRemovedUsers,\n ManageChannelRemovedUsers,\n ManageGroupUserPermissionsCreate,\n ManageGroupUserPermissions,\n ManageGroupRecentActions,\n ManageGroupAdminRights,\n ManageGroupNewAdminRights,\n ManageGroupMembers,\n ManageGroupAddAdmins,\n StickerSearch,\n GifSearch,\n PollResults,\n AddingMembers,\n ManageInvites,\n ManageEditInvite,\n ManageReactions,\n ManageInviteInfo,\n ManageJoinRequests,\n}\n\nconst RightHeader: FC = ({\n chatId,\n isColumnOpen,\n isProfile,\n isSearch,\n isManagement,\n isStatistics,\n isStickerSearch,\n isGifSearch,\n isPollResults,\n isAddingChatMembers,\n profileState,\n managementScreen,\n canAddContact,\n userId,\n canManage,\n isChannel,\n onClose,\n onScreenSelect,\n messageSearchQuery,\n stickerSearchQuery,\n gifSearchQuery,\n shouldSkipAnimation,\n isEditingInvite,\n canViewStatistics,\n currentInviteInfo,\n}) => {\n const {\n setLocalTextSearchQuery,\n setStickerSearchQuery,\n setGifSearchQuery,\n searchTextMessagesLocal,\n toggleManagement,\n openHistoryCalendar,\n openAddContactDialog,\n toggleStatistics,\n setEditingExportedInvite,\n deleteExportedChatInvite,\n } = getActions();\n\n // eslint-disable-next-line no-null/no-null\n const backButtonRef = useRef(null);\n const [isDeleteDialogOpen, openDeleteDialog, closeDeleteDialog] = useFlag();\n\n const handleEditInviteClick = useCallback(() => {\n setEditingExportedInvite({ chatId: chatId!, invite: currentInviteInfo! });\n onScreenSelect(ManagementScreens.EditInvite);\n }, [chatId, currentInviteInfo, onScreenSelect, setEditingExportedInvite]);\n\n const handleDeleteInviteClick = useCallback(() => {\n deleteExportedChatInvite({ chatId: chatId!, link: currentInviteInfo!.link });\n onScreenSelect(ManagementScreens.Invites);\n closeDeleteDialog();\n }, [chatId, closeDeleteDialog, currentInviteInfo, deleteExportedChatInvite, onScreenSelect]);\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 openAddContactDialog({ userId });\n }, [openAddContactDialog, 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.ChannelRemovedUsers ? (\n HeaderContent.ManageChannelRemovedUsers\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.Invites ? (\n HeaderContent.ManageInvites\n ) : managementScreen === ManagementScreens.EditInvite ? (\n HeaderContent.ManageEditInvite\n ) : managementScreen === ManagementScreens.GroupAddAdmins ? (\n HeaderContent.ManageGroupAddAdmins\n ) : managementScreen === ManagementScreens.Reactions ? (\n HeaderContent.ManageReactions\n ) : managementScreen === ManagementScreens.InviteInfo ? (\n HeaderContent.ManageInviteInfo\n ) : managementScreen === ManagementScreens.JoinRequests ? (\n HeaderContent.ManageJoinRequests\n ) : undefined // Never reached\n ) : isStatistics ? (\n HeaderContent.Statistics\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('BlockedUsers')}

;\n case HeaderContent.ManageChannelRemovedUsers:\n return

{lang('ChannelBlockedUsers')}

;\n case HeaderContent.ManageGroupUserPermissionsCreate:\n return

{lang('ChannelAddException')}

;\n case HeaderContent.ManageGroupUserPermissions:\n return

{lang('UserRestrictions')}

;\n case HeaderContent.ManageInvites:\n return

{lang('lng_group_invite_title')}

;\n case HeaderContent.ManageEditInvite:\n return

{isEditingInvite ? lang('EditLink') : lang('NewLink')}

;\n case HeaderContent.ManageInviteInfo:\n return (\n <>\n

{lang('InviteLink')}

\n
\n {currentInviteInfo && !currentInviteInfo.isRevoked && (\n \n \n \n )}\n {currentInviteInfo && currentInviteInfo.isRevoked && (\n <>\n \n \n \n \n \n )}\n
\n \n );\n case HeaderContent.ManageJoinRequests:\n return

{isChannel ? lang('SubscribeRequests') : lang('MemberRequests')}

;\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.Statistics:\n return

{lang('Statistics')}

;\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 case HeaderContent.ManageReactions:\n return

{lang('Reactions')}

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

Profile

\n
\n {canAddContact && (\n \n \n \n )}\n {canManage && (\n \n \n \n )}\n {canViewStatistics && (\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 const isEditingInvite = Boolean(chatId && global.management.byChatId[chatId]?.editingInvite);\n const canViewStatistics = chat?.fullInfo?.canViewStatistics;\n const currentInviteInfo = chatId ? global.management.byChatId[chatId]?.inviteInfo?.invite : undefined;\n\n return {\n canManage,\n canAddContact,\n canViewStatistics,\n isChannel,\n userId: user?.id,\n messageSearchQuery,\n stickerSearchQuery,\n gifSearchQuery,\n isEditingInvite,\n currentInviteInfo,\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 '../../../global/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 );\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 { getActions, withGlobal } from '../../global';\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 '../../global/helpers';\nimport {\n selectChatMessages,\n selectChat,\n selectCurrentMediaSearch,\n selectIsRightColumnShown,\n selectTheme,\n selectActiveDownloadIds,\n selectUser,\n} from '../../global/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';\nimport { useIntersectionObserver } from '../../hooks/useIntersectionObserver';\n\ntype OwnProps = {\n chatId: 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;\nconst INTERSECTION_THROTTLE = 500;\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 focusMessage,\n loadProfilePhotos,\n setNewChatMembersDialogState,\n } = getActions();\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,\n loadMoreMembers,\n loadCommonChats,\n searchMediaMessagesLocal,\n tabType,\n mediaSearchType,\n members,\n commonChatIds,\n usersById,\n userStatusesById,\n chatsById,\n chatMessages,\n foundIds,\n chatId,\n 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 { observe: observeIntersectionForMedia } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE,\n });\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 openChat({ id });\n }, [openChat]);\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 canRenderContent = 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 renderContent() {\n if (!viewportIds || !canRenderContent || !chatMessages) {\n const noSpinner = isFirstTab && !canRenderContent;\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 {renderContent()}\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 }): StateProps => {\n const chat = selectChat(global, chatId);\n const chatMessages = selectChatMessages(global, 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 const activeDownloadIds = selectActiveDownloadIds(global, chatId);\n\n let hasCommonChatsTab;\n let resolvedUserId;\n let user;\n if (isUserId(chatId)) {\n resolvedUserId = chatId;\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\nconst useCacheBuster = () => {\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\nexport default useCacheBuster;\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 } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './Statistics';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst StatisticsAsync: FC = (props) => {\n const Statistics = useModuleLoader(Bundles.Extra, 'Statistics');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Statistics ? : ;\n};\n\nexport default StatisticsAsync;\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 { getActions, getGlobal, withGlobal } from '../../global';\n\nimport {\n ApiChat, ApiChatMember, ApiUpdateConnectionStateType,\n} from '../../api/types';\nimport { NewChatMembersProgress } from '../../types';\n\nimport { unique } from '../../util/iteratees';\nimport { selectChat } from '../../global/selectors';\nimport {\n filterUsersByName, isChatChannel, isUserBot, sortChatIds,\n} from '../../global/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 } = getActions();\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 { getActions, withGlobal } from '../../global';\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 '../../global/selectors';\nimport useLayoutEffectWithPrevDeps from '../../hooks/useLayoutEffectWithPrevDeps';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useHistoryBack from '../../hooks/useHistoryBack';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\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 Statistics from './statistics/Statistics.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 isChatSelected: boolean;\n shouldSkipHistoryAnimations?: boolean;\n nextManagementScreen?: ManagementScreens;\n};\n\nconst CLOSE_ANIMATION_DURATION = 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 isChatSelected,\n shouldSkipHistoryAnimations,\n nextManagementScreen,\n}) => {\n const {\n toggleChatInfo,\n toggleManagement,\n closeLocalTextSearch,\n setStickerSearchQuery,\n setGifSearchQuery,\n closePollResults,\n addChatMembers,\n setNewChatMembersDialogState,\n setEditingExportedInvite,\n toggleStatistics,\n setOpenedInviteInfo,\n requestNextManagementScreen,\n } = getActions();\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;\n const isSearch = contentKey === RightColumnContent.Search;\n const isManagement = contentKey === RightColumnContent.Management;\n const isStatistics = contentKey === RightColumnContent.Statistics;\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.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 case ManagementScreens.Invites:\n case ManagementScreens.Reactions:\n case ManagementScreens.JoinRequests:\n case ManagementScreens.ChannelRemovedUsers:\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 case ManagementScreens.EditInvite:\n case ManagementScreens.InviteInfo:\n setManagementScreen(ManagementScreens.Invites);\n setOpenedInviteInfo({ invite: undefined });\n setEditingExportedInvite({ chatId, invite: undefined });\n break;\n }\n\n break;\n }\n case RightColumnContent.Statistics:\n toggleStatistics();\n break;\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, closePollResults, setNewChatMembersDialogState,\n managementScreen, toggleManagement, closeLocalTextSearch, setStickerSearchQuery, setGifSearchQuery,\n setEditingExportedInvite, chatId, setOpenedInviteInfo, toggleStatistics,\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 }, CLOSE_ANIMATION_DURATION);\n }, [isOpen]);\n\n useEffect(() => {\n if (nextManagementScreen) {\n setManagementScreen(nextManagementScreen);\n requestNextManagementScreen(undefined);\n }\n }, [nextManagementScreen, requestNextManagementScreen]);\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(([prevChatId]) => {\n if (prevChatId !== chatId) {\n setProfileState(ProfileState.Profile);\n setManagementScreen(ManagementScreens.Initial);\n }\n }, [chatId]);\n\n useHistoryBack(isChatSelected && (\n contentKey === RightColumnContent.ChatInfo\n || 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 return (\n \n );\n case RightColumnContent.Search:\n return ;\n case RightColumnContent.Management:\n return (\n \n );\n\n case RightColumnContent.Statistics:\n return ;\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 const nextManagementScreen = chatId ? global.management.byChatId[chatId]?.nextScreen : undefined;\n\n return {\n contentKey: selectRightColumnContentKey(global),\n chatId,\n threadId,\n isChatSelected: Boolean(chatId && areActiveChatsLoaded),\n shouldSkipHistoryAnimations: global.shouldSkipHistoryAnimations,\n nextManagementScreen,\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 { getActions, withGlobal } from '../../global';\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 '../../global/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 } = getActions();\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, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport { OwnProps } from './NewContactModal';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst NewContactModalAsync: FC = (props) => {\n const { isOpen } = props;\n const NewContactModal = useModuleLoader(Bundles.Extra, 'NewContactModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return NewContactModal ? : undefined;\n};\n\nexport default memo(NewContactModalAsync);\n","import React, {\n FC, useEffect, memo, useCallback,\n} from '../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../global';\n\nimport { LangCode } from '../../types';\nimport { ApiMessage, ApiUpdateAuthorizationStateType, ApiUpdateConnectionStateType } from '../../api/types';\n\nimport '../../global/actions/all';\nimport {\n BASE_EMOJI_KEYWORD_LANG, DEBUG, INACTIVE_MARKER, PAGE_TITLE,\n} from '../../config';\nimport {\n selectChatMessage,\n selectIsForwardModalOpen,\n selectIsMediaViewerOpen,\n selectIsRightColumnShown,\n selectIsServiceChatReady,\n} from '../../global/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 { getAllNotificationsCount } from '../../util/folderManager';\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 StickerSetModal from '../common/StickerSetModal.async';\nimport UnreadCount from '../common/UnreadCounter';\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 GroupCall from '../calls/group/GroupCall.async';\nimport ActiveCallHeader from '../calls/ActiveCallHeader.async';\nimport CallFallbackConfirm from '../calls/CallFallbackConfirm.async';\nimport NewContactModal from './NewContactModal.async';\n\nimport './Main.scss';\n\ntype StateProps = {\n connectionState?: ApiUpdateConnectionStateType;\n authState?: ApiUpdateAuthorizationStateType;\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 newContactUserId?: string;\n newContactByPhoneNumber?: boolean;\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 connectionState,\n authState,\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 newContactUserId,\n newContactByPhoneNumber,\n}) => {\n const {\n sync,\n loadAnimatedEmojis,\n loadNotificationSettings,\n loadNotificationExceptions,\n updateIsOnline,\n loadTopInlineBots,\n loadEmojiKeywords,\n loadCountryList,\n loadAvailableReactions,\n loadStickerSets,\n loadAddedStickers,\n loadFavoriteStickers,\n ensureTimeFormat,\n openStickerSetShortName,\n checkVersionNotification,\n loadAppConfig,\n } = getActions();\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 useEffect(() => {\n if (connectionState === 'connectionStateReady' && authState === 'authorizationStateReady') {\n sync();\n }\n }, [connectionState, authState, sync]);\n\n // Initial API calls\n useEffect(() => {\n if (lastSyncTime) {\n updateIsOnline(true);\n loadAppConfig();\n loadAvailableReactions();\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, loadAvailableReactions, loadAppConfig,\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 (lastSyncTime) {\n if (!addedSetIds) {\n loadStickerSets();\n loadFavoriteStickers();\n } else {\n loadAddedStickers();\n }\n }\n }, [lastSyncTime, 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 = getAllNotificationsCount();\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 = getAllNotificationsCount() - 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 );\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 connectionState: global.connectionState,\n authState: global.authState,\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 newContactUserId: global.newContact?.userId,\n newContactByPhoneNumber: global.newContact?.isByPhoneNumber,\n };\n },\n)(Main));\n","import { getActions, getGlobal } from '../global';\n\nimport { DEBUG } from '../config';\n\n// eslint-disable-next-line import/no-cycle\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 getActions().initApi();\n}\n"],"names":["closeLocalTextSearch","global","chatId","threadId","selectCurrentMessageList","updateLocalTextSearch","replaceLocalTextSearchResults","undefined","addActionHandler","actions","payload","query","chatThreadKey","buildChatThreadKey","currentQuery","localTextSearch","byChatThreadKey","MEMO_EMPTY_ARRAY","mediaType","updateLocalMediaSearchType","id","MAIN_THREAD_ID","type","shouldReplaceHistory","currentMessageList","replaceThreadParam","exitMessageSelectMode","isStatisticsShown","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","copyTextForMessages","messageIds","lang","langProvider","chatMessages","selectChatMessages","result","map","filter","message","selectAllowedMessageActions","canCopy","sort","message1","message2","reduce","acc","sender","selectSender","push","getSenderTitle","getMessageSummaryText","copyTextToClipboard","join","scrollOffset","messageId","paramName","text","viewportIds","selectViewportIds","lastOwnEditableMessageId","findLast","Boolean","canEdit","replyingToId","selectReplyingToId","selectIsViewportNewest","chatMessageKeys","Object","keys","newIndex","toString","length","Number","chat","selectChat","lastMessage","threadInfo","selectThreadInfo","lastMessageId","setReplyingToId","focusMessage","origin","volume","playbackRate","isMuted","audioPlayer","selectIsRightColumnShown","pollResults","voters","window","setTimeout","getGlobal","noHighlight","replyStack","selectReplyStack","pop","focusLastMessage","messageListType","groupedId","groupedChatId","replyMessageId","isResizingContainer","ids","selectForwardedMessageIdsByGroupId","shouldSwitchChat","clearTimeout","newGlobal","updateFocusedMessage","updateFocusDirection","FocusDirection","includes","direction","loadViewportMessages","fromChatId","groupedMessageIds","selectMessageIdsByGroupId","isModalShown","closeMediaViewer","selectedMessages","openForwardMenu","byChatId","activeDownloads","canDownload","forEach","downloadMessageMedia","selectCurrentChat","enterMessageSelectMode","childMessageIds","withShift","toggleMessageSelection","shouldShowContextMenuHint","disableContextMenuHint","showNotification","IS_TOUCH_ENV","isPollModalOpen","currentVersion","APP_VERSION","slice","serviceNotifications","find","version","SERVICE_NOTIFICATIONS_USER_ID","date","getServerTime","serverTimeOffset","content","parseMessageInput","versionNotification","isOutgoing","createServiceNotification","serviceChat","maxId","Math","max","fractionalPart","floor","serviceNotification","isUnread","apiUpdate","reactorModal","seenByModal","globalSearch","updateGlobalSearch","globalResults","localResults","resultsByType","fetchingStatus","chats","recentlyFoundChatIds","newRecentIds","unshift","updateGlobalSearchContent","stickers","search","resultIds","gifs","offsetId","results","updateUserSearch","globalUserIds","localUserIds","userId","newContact","isByPhoneNumber","closeNewContactDialog","action","leftColumnWidth","management","isActive","screen","nextScreen","IS_SINGLE_COLUMN_LAYOUT","IS_TABLET_COLUMN_LAYOUT","isLeftColumnShown","messageLists","emoji","recentEmojis","newEmojis","e","sticker","recent","hash","newStickers","s","notification","localId","generateIdFor","newNotifications","notifications","existingNotificationIndex","findIndex","n","splice","data","hasErrorKey","getReadableErrorText","newDialogs","dialogs","existingErrorIndex","err","url","safeLinkModalUrl","selectedAt","historyCalendarSelectedAt","payment","isPaymentModalOpen","clearPayment","closeInvoice","error","avatarOwnerId","profilePhotoIndex","mediaViewer","uploadProgressCallbacks","Map","runDebouncedForMarkRead","debounce","cb","async","isOutlying","isBudgetPreload","addOffset","LoadMoreDirection","round","MESSAGE_LIST_SLICE","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","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","cached","setsById","loadStickers","stickerSetId","pause","recentStickers","loadRecentStickers","favorite","favoriteStickers","loadFavoriteStickers","greeting","featured","featuredStickers","loadFeaturedStickers","stickerSetShortName","stickerSetAccessHash","stickerSet","selectStickerSet","accessHash","packs","updateStickerSet","currentEmoji","forEmoji","rebuildStickersForEmoji","replaceAnimatedEmojis","loadAnimatedEmojis","animatedEmojiEffects","loadAnimatedEmojiEffects","saved","savedGifs","loadSavedGifs","gif","shouldUnsave","newGifs","unfave","unfaveSticker","installedDate","language","currentEmojiKeywords","emojiKeywords","isLoading","fromVersion","keywords","searchStickers","title","searchWords","updateStickersForEmoji","loadStickersForEmoji","openedStickerSetShortName","searchMessagesGlobal","offsetRate","maxDate","minDate","localResult","GLOBAL_SEARCH_SLICE","totalCount","nextOffsetId","nextRate","currentSearchQuery","selectCurrentGlobalSearchQuery","updateGlobalSearchFetchingStatus","addMessages","updateGlobalSearchResults","searchSharedMedia","SHARED_MEDIA_SLICE","newFoundIds","currentSearch","selectCurrentMediaSearch","updateLocalMediaSearchResults","localChats","localUsers","globalChats","globalUsers","chatIds","userIds","searchChats","timestampPlusDay","foundIds","selectCurrentTextSearch","topMessageId","MESSAGE_SEARCH_SLICE","updateLocalTextSearchResults","searchTextMessages","currentType","currentResults","timestamp","getActions","searchMessagesByDate","ManagementProgress","username","updateManagementProgress","updateManagement","isUsernameAvailable","isChatBasicGroup","invite","editingInvite","update","inviteInfo","adminId","isRevoked","admin","revokedInvites","invites","link","expireDate","usageLimit","isRequestNeeded","oldInvite","newInvite","current","managementState","offsetDate","offsetUserId","offsetUser","currentInviteInfo","importers","isRequested","requesters","joinRequests","isApproved","targetChat","importer","recentRequesterIds","requestsPending","settings","releaseStatusTimeout","loadTopMessages","DEBUG","console","log","isSyncing","loadAllChats","preloadTopChatMessages","listType","shouldReplace","onReplace","areMessagesLoaded","draftsByChatId","editingDraft","selectEditingDraft","currentChatId","currentThreadId","currentChat","newCurrentChatId","currentMessageListInfo","originChannelId","currentMessageListInfoOrigin","resultOrigin","byIdOrigin","listedIdsOrigin","threadsById","updateChats","updateUsers","updateThread","audioChatId","audioMessageId","closeAudioPlayer","loadAndReplaceMessages","lastSyncTime","initFolderManager","runDebouncedForFetchFullUser","runThrottledForSearch","replaceInlineBotSettings","inlineBotSettings","inlineBots","byUsername","replaceInlineBotsIsLoading","userStatusesById","replaceUserStatuses","statusesById","topPeers","lastRequestedAt","loadTopUsers","contactList","getCompareString","lastName","firstName","collator","Intl","Collator","sortedUsers","compare","isSelf","loadContactList","isUserBot","commonChats","isFullyLoaded","updateUser","shouldSharePhoneNumber","updateChatMutedState","isContact","phoneNumber","phone","updateContact","deleteContact","profileId","isPrivate","isUserId","photos","userSearch","updateUserSearchFetchingStatus","searchUsers","userOrChat","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","scheduleDate","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","nativeProvider","credentials","publishableKey","selectProviderPublishableKey","k","buildQueryString","cardNumber","expiryMonth","expiryYear","cvv","zip","country","response","fetch","method","headers","Authorization","json","getStripeError","setStripeCardInfo","sendStripeCredentials","publicToken","selectProviderPublicToken","card","number","replace","expiration_month","expiration_year","security_code","DEBUG_PAYMENT_SMART_GLOCAL","Accept","body","JSON","stringify","status","setSmartGlocalCardInfo","token","sendSmartGlocalCredentials","shippingOptionId","saveCredentials","formId","selectPaymentFormId","requestInfoId","selectPaymentRequestId","requestedInfoId","sendPaymentForm","save","selectStripeCredentials","selectSmartGlocalCredentials","MAX_MESSAGES_LIST_WIDTH","SIDE_COLUMN_MAX_WIDTH","MIN_LEFT_COLUMN_WIDTH","subtractXForEmojiInteraction","x","windowWidth","windowSize","width","MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","min","MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN","interactionLocalId","availableReaction","aroundAnimation","mediaLoader","ApiMediaFormat","centerIcon","availableReactions","y","localEffect","startSize","isReversed","activeEmojiInteraction","animatedEffect","INTERACTION_RANDOM_OFFSET","activeEmojiInteractions","interactions","emoticon","selectLocalAnimatedEmojiEffectByName","timestamps","reaction","selectDefaultReaction","isMessageLocal","sendReaction","isInDocumentGroup","isInAlbum","documentGroupFirstMessageId","reactions","some","isChosen","animationLevel","byKey","ANIMATION_LEVEL_MAX","activeReactions","omit","recentReactions","canSeeList","addMessageReaction","appConfig","defaultReaction","reactors","isGroup","recentTopMessages","msgId","updateStatistics","name","isPercentage","dcId","statisticsDcId","updateStatisticsGraph","areDeepEqual","value1","value2","type1","isArray1","Array","isArray","array1","array2","every","member1","object1","object2","key1","noTopChatsRequest","selectIsChatListed","loadTopChats","newProfilePhoto","closeMessageNotifications","selectChatListType","updateChatListIds","isNotJoined","requestChatUpdate","leaveChat","typingStatus","senderId","isFromScheduled","hasUnreadMention","unreadMentionsCount","notifyAboutMessage","getMessageRecentReaction","messageUpdate","channelId","selectCommonBoxChatId","folderId","ARCHIVED_FOLDER_ID","orderedPinnedIds","isPinned","newOrderedPinnedIds","MAX_ACTIVE_PINNED_CHATS","listIds","active","pinnedId","updateChatListType","folder","chatFoldersById","chatFolders","newChatFoldersById","pick","newOrderedIds","orderedId","folders","recommended","replacedMembers","addedMember","deletedMemberId","shouldUpdate","members","deleteIndex","adminMembers","isOwner","isAdmin","membersCount","photo","formattedText","loadChatJoinRequests","ANIMATION_DELAY","updateWithLocalMedia","isScheduled","currentMessage","video","document","getMessageContent","blobUrl","thumbnail","isPreloadedGlobally","previewBlobUrl","updateScheduledMessage","updateThreadUnread","selectThreadByMessage","originMessage","updateListedAndViewportIds","firstMessageId","isUnreadChatNotLoaded","addViewportId","messagesCount","firstUnreadId","candidateGlobal","updateChatLastMessage","force","currentLastMessage","findLastMessage","deleteMessages","newLastMessage","threadIdsToUpdate","deleteChatMessages","requestThreadInfoUpdate","chatsIdsToUpdate","commonBoxChatId","shouldForceReply","updateThreadInfo","newMessage","selectIsMessageInCurrentMessageList","delayedGlobal","getMessageText","localEmoji","selectLocalAnimatedEmoji","selectLocalAnimatedEmojiEffect","scheduledIds","selectScheduledIds","selectIsChatWithBot","selectScheduledMessages","deleteChatScheduledMessages","thread","markMessageListRead","currentPinnedIds","selectPinnedIds","newPinnedIds","newTheadInfo","messagesById","loadFullChat","scheduledMessages","deleteScheduledMessages","pollId","pollUpdate","selectChatMessageByPollId","updatedPoll","updatedResults","chosenAnswers","chosenAnswer","chosenAnswerIndex","recentVoterIds","totalVoters","newRecentVoterIds","newTotalVoters","targetOption","targetOptionIndex","updatedOption","votersCount","selectIsServiceChatReady","currentReactions","shouldNotify","checkIfReactionAdded","isReaction","flushStatusUpdatesThrottled","pendingStatusUpdates","statusUpdate","targetUser","isBlocked","addBlockedContact","privacy","key","rules","setConfirmPaymentUrl","updateNotifySettings","peerType","shouldShowPreviews","addNotifyException","twoFaSettings","call","connectionState","groupCalls","activeGroupCallId","leaveGroupCall","shouldRemove","removeGroupCall","updateGroupCall","participantsCount","groupCallId","participants","participant","updateGroupCallParticipant","useBeforeUnload","callback","useEffect","onBeforeUnload","metaViewport","querySelector","defaultViewportContent","getAttribute","allowedZoomViewportContent","preventEvent","preventDefault","memo","isForAppBadge","useFolderManagerForUnreadCounters","unreadNotificationsCount","getAllNotificationsCount","updateAppBadge","className","formatIntegerCompact","ConnectionStatus","useConnectionStatus","hasMiddleHeader","isMinimized","isDisabled","isOnline","setIsOnline","useState","navigator","onLine","handleChange","addEventListener","removeEventListener","useBrowserOnline","syncing","online","waitingForNetwork","toLowerCase","connectionStatus","connectionStatusPosition","connectionStatusText","onClick","useLang","dir","isRtl","Spinner","color","Transition","activeKey","Button","size","ANIMATION_LEVEL_OPTIONS","withGlobal","searchQuery","chatsById","isConnectionStatusMinimized","globalSearchChatId","searchDate","theme","selectTheme","isMessageListOpen","areChatsLoaded","contactsFilter","onSearchQuery","onSelectSettings","onSelectContacts","onSelectArchived","onReset","shouldSkipTransition","openTipsChat","setGlobalSearchDate","setSettingOption","setGlobalSearchChatId","hasMenu","LeftColumnContent","selectedSearchDate","useMemo","formatDateToString","archivedUnreadChatsCount","values","total","isChatArchived","withOtherVersions","location","hostname","MainButton","onTrigger","isOpen","ripple","ariaLabel","buildClassName","handleSearchFocus","useCallback","toggleConnectionStatus","handleSelectSaved","handleDarkModeToggle","stopPropagation","newTheme","shouldUseSystemTheme","switchTheme","handleAnimationLevelChange","newLevel","_","classList","toggle","isSearchFocused","searchInputPlaceholder","DropdownMenu","trigger","footer","APP_NAME","APP_REVISION","MenuItem","icon","Switcher","label","checked","noAnimation","langCode","href","FEEDBACK_URL","setPermanentWebVersion","clearWebsync","disableHistoryBack","SearchInput","inputId","parentContainerClassName","focused","spinnerColor","spinnerBackgroundColor","placeholder","autoComplete","canClose","onChange","onFocus","onSpinnerClick","PickerSelectedItem","clickArg","chatOrUserId","ShowTransition","isCustom","orderedFolderIds","activeChatFolder","shouldSkipHistoryAnimations","foldersDispatch","onScreenSelect","loadChatFolders","setActiveChatFolder","transitionRef","useRef","displayedFolders","folderCountersById","folderTabs","ALL_FOLDER_ID","badgeCount","chatsCount","isBadgeActive","notificationsCount","handleSwitchTab","forceOnHeavyAnimation","captureEvents","selectorToPreventScroll","onSwipe","SwipeDirection","isNotInAllTabRef","captureEscKeyListener","useHistoryBack","handleKeyDown","ctrlKey","shiftKey","startsWith","digit","shouldRender","shouldRenderPlaceholder","transitionClassNames","useShowTransition","renderCurrentTab","activeFolder","ChatList","folderType","TabList","tabs","activeTab","onSwitchTab","ref","renderCount","props","LeftSearch","useModuleLoader","Bundles","Loading","ContactList","isShown","onNewPrivateChat","onNewChannel","onNewGroup","isMenuOpen","setIsMenuOpen","fabClassName","tabIndex","Menu","positionX","positionY","autoClose","onClose","TRANSITION_RENDER_COUNT","closeTimeout","onContentChange","isNewChatButtonShown","setIsNewChatButtonShown","isMouseInside","handleSelectSettings","handleSelectContacts","handleSelectNewChannel","handleSelectNewGroup","handleSelectArchived","handleMouseEnter","handleMouseLeave","autoCloseTimeout","shouldRenderUpdateButton","updateButtonClassNames","handleUpdateClick","isAppOutdated","markIsAppOutdated","useFlag","timeout","reload","useAppOutdatedCheck","onMouseEnter","onMouseLeave","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","remove","style","handleMouseMove","newWidth","ceil","clientX","stopDrag","cleanup","offsetWidth","add","useResize","handleSettingsScreenSelect","LAYERS_ANIMATION_NAME","currentScreen","isChannel","onMouseDown","onMouseUp","onDoubleClick","setSize","handleResize","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","canViewStatistics","pendingJoinRequests","canExpandActions","joinChannel","openLocalTextSearch","restartBot","openCallFallbackConfirm","requestNextManagementScreen","menuButtonRef","menuPosition","setMenuPosition","handleHeaderMenuOpen","rect","getBoundingClientRect","right","bottom","handleHeaderMenuClose","handleHeaderMenuHide","handleSubscribeClick","handleStartBot","handleRestartBot","handleJoinRequestsClick","ManagementScreens","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","renderMessageSummary","isUnpinDialogOpen","openUnpinDialog","closeUnpinDialog","handleUnpinMessage","ConfirmDialog","confirmLabel","confirmHandler","getPictogramDimensions","src","alt","renderPictogram","RippleEffect","scaleImage","image","ratio","outputType","Blob","URL","createObjectURL","img","Image","onload","scale","blob","Error","finally","revokeObjectURL","steppedScale","bitmap","createImageBitmap","resizeWidth","resizeHeight","resizeQuality","res","canvas","createElement","ctx","getContext","transferFromImageBitmap","drawImage","toBlob","oc","octx","mul","cur","LOGO_DIMENSIONS","MINIMAL_SIZE","audio","voice","fileName","artist","performer","getTranslation","album","getChatTitle","audioCoverHash","getAudioHasCover","avatarHash","getChatAvatarHash","media","thumbnailSizes","preferred","AVATAR_FULL_DIMENSIONS","getCoverSize","fn","deps","defaultValue","setIsLoading","setError","setResult","wasCancelled","telegramLogoPath","resizeImage","makeGoodArtwork","useAsync","buildMediaMetadata","artwork","noUi","setAudioPlayerVolume","setAudioPlayerPlaybackRate","setAudioPlayerMuted","isVoice","senderName","mediaData","mediaMetadata","useMessageMediaMetadata","playPause","stop","isPlaying","requestNextTrack","requestPreviousTrack","isFirst","isLast","setVolume","toggleMuted","setPlaybackRate","useAudioPlayer","makeTrackId","getMediaDuration","isVoicePlaying","handleClick","handleClose","clearMediaSession","handleVolumeChange","handleVolumeClick","handlePlaybackClick","volumeIcon","renderText","renderAudio","subtitle","renderVoice","withClickPropagation","RangeSlider","bold","groupCall","selectChatGroupCall","usersById","isLoaded","isCallNotEmpty","hasPinnedOffset","joinGroupCall","subscribeToGroupCallUpdates","handleJoinGroupCall","fetchedParticipants","isUser","subscribed","p","Avatar","openAddContactDialog","blockContact","reportSpam","deleteChat","leaveChannel","deleteChatUser","deleteHistory","toggleChatArchived","hideChatReportPanel","isBlockUserModalOpen","openBlockUserModal","closeBlockUserModal","shouldReportSpam","setShouldReportSpam","shouldDeleteChat","setShouldDeleteChat","isAutoArchived","canReportSpam","canAddContact","canBlockContact","isBasicGroup","handleAddContact","handleConfirmBlock","contactId","handleCloseReportPanel","handleChatReportSpam","isText","getUserFirstOrLastName","getUserFullName","isButtonsInOneRow","confirmIsDestructive","Checkbox","onCheck","audioMessage","pinnedIds","state","isSelectModeActive","isChatWithBot","currentTransitionKey","assign","pinnedMessageId","topMessageSender","selectForwardedSender","pinnedMessageIds","canUnpin","firstPinnedMessage","isReady","openChatWithInfo","pinMessage","openPreviousChat","toggleLeftColumn","isBackButtonActive","pinnedMessageIndex","setPinnedMessageIndex","pinnedMessage","pinnedMessagesCount","chatTitleLength","topMessageTitle","useEnsureMessage","useWindowSize","isLeftColumnHideable","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","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","hasChatSettings","shouldShowChatReportPanel","chatReportPanelClassNames","renderingChatSettings","useCurrentOrPrev","shouldRenderAudioPlayer","audioPlayerClassNames","renderingAudioMessage","shouldRenderPinnedMessage","pinnedMessageClassNames","renderingPinnedMessage","renderingPinnedMessagesCount","renderingCanUnpin","renderingPinnedMessageTitle","canRevealTools","componentEl","renderBackButton","asClose","withUnreadCounter","isAudioPlayerRendered","PrivateChatInfo","withDots","withFullInfo","withMediaViewer","withUpdatingStatus","noRtl","GroupChatInfo","getMessageKey","isAlbum","messageOrAlbum","groupMessages","currentAlbum","currentSenderGroup","currentDateGroup","originalDate","datetime","getDayStartAt","senderGroups","dateGroups","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","stretchFactor","finalWidth","finalHeight","isSmall","accumulate","list","initValue","accumulator","item","clamp","num","low","high","calculateContainerSize","layout","styles","dimensions","sides","calculateAlbumLayout","ratios","getRatios","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","QUICK_REACTION_AREA_WIDTH","QUICK_REACTION_AREA_HEIGHT","GROUP_MESSAGE_HOVER_ATTRIBUTE","useOuterHandlers","selectMessage","isInSelectMode","canReply","isProtected","onContextMenu","handleBeforeContextMenu","isContextMenuShown","contentRef","shouldHandleMouseLeave","sendDefaultReaction","isQuickReactionVisible","markQuickReactionVisible","unmarkQuickReactionVisible","isSwiped","markSwiped","unmarkSwiped","doubleTapTimeoutRef","startedAt","onRelease","handleMouseDown","preventMessageInputBlur","clearInterval","pageX","pageY","handleDoubleTap","target","contains","handleTap","handleContextMenu","stopEvent","matches","handleDoubleClick","handleContentDoubleClick","container","clientY","isVisibleX","isVisibleY","handleSendQuickReaction","currentTarget","lastGroupElement","getLastElementInDocumentGroup","removeAttribute","handleDocumentGroupMouseLeave","handleDocumentGroupMouseEnter","setAttribute","nextElementSibling","ContextMenuContainer","targetUserIds","targetChatId","targetMessageId","targetMessage","selectIsMessageFocused","focusedMessage","isChat","senderUser","senderChat","observeIntersection","isEmbedded","appearanceOrder","isLastInList","useOnIntersect","noAppearanceAnimation","markShown","targetUsers","renderActionMessageText","asTextWithSpoilers","isContextMenuOpen","contextMenuPosition","handleContextMenuClose","handleContextMenuHide","useContextMenuHandlers","getMessageHtmlId","customText","isIntersecting","useIsIntersecting","isRoundVideo","getMessageRoundVideo","senderTitle","draggable","activeReaction","isInMeta","stopActiveReaction","r","centerIconId","effectId","mediaDataCenterIcon","mediaDataEffect","shouldPlay","shouldRenderAnimation","animationClassNames","handleEnded","isAnimationLoaded","markAnimationLoaded","unmarkAnimationLoaded","shouldRenderStatic","ReactionStaticEmoji","AnimatedSticker","animationData","play","noLoop","onLoad","onEnded","outgoingStatus","signature","withReactions","withReactionOffset","reactionMessage","isActivated","markActivated","createDateTime","formatDateTimeToString","editDateTime","isEdited","editDate","forwardedDateTime","views","formatTime","MessageOutgoingStatus","observeIntersectionForPlaying","shouldLoop","isModalOpen","openModal","closeModal","isLottie","isVideo","canDisplayVideo","IS_WEBM_SUPPORTED","isMemojiSticker","NO_STICKER_SET_ID","shouldLoad","mediaHash","previewMediaHash","previewUrl","getMessageMediaFormat","isMediaLoaded","isLottieLoaded","markLottieLoaded","isMediaReady","useMediaTransition","getStickerDimensions","thumbClassName","stickerClassName","safePlay","autoPlay","playsInline","loop","muted","fromSticker","useBlurredMediaThumbRef","fullMediaData","useCanvasBlur","IS_CANVAS_FILTER_SUPPORTED","SELECTED_APPENDIX_COLORS","dark","outgoing","incoming","light","getCustomAppendixBg","inSelectMode","isSelected","getImageData","getAppendixColorFromImage","canAutoLoad","uploadProgress","nonInteractive","shouldAffectAppendix","isDownloading","onCancelUpload","localBlobUrl","isLoadAllowed","setIsLoadAllowed","loadProgress","useMediaWithLoadProgress","thumbRef","downloadProgress","isUploading","isTransferring","transferProgress","getMediaTransferState","wasLoadDisabled","usePrevious","shouldRenderSpinner","spinnerClassNames","shouldRenderDownloadButton","downloadButtonClassNames","isAllowed","contentEl","appendixBg","setProperty","CUSTOM_APPENDIX_ATTRIBUTE","ProgressSpinner","useVideoAutoPause","playerRef","canPlay","wasPlaying","paused","canPlayRef","freezePlaying","unfreezePlaying","unfreezePlayingOnRaf","fastRaf","useBackgroundMode","useHeavyAnimationCheck","canAutoPlay","videoRef","getMessageWebPageVideo","isPlayAllowed","setIsPlayAllowed","previewClassNames","isInline","isBuffered","bufferingHandlers","useBuffering","shouldRenderPlayButton","playButtonClassNames","playProgress","setPlayProgress","handleTimeUpdate","currentTime","duration","useVideoCleanup","cancelMessageMediaDownload","onTimeUpdate","isGif","formatMediaDuration","contact","countryList","phoneCodes","phoneCodeList","formatPhoneNumberWithCode","getPercentage","toFixed","answer","voteResults","maxVotersCount","correctResults","shouldAnimate","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","inPreview","onMediaClick","onCancelMediaTransfer","webPage","getMessageWebPage","isSquarePhoto","handleMediaClick","siteName","displayUrl","isMediaInteractive","truncatedDescription","trimText","SafeLink","getMessageInvoice","amount","currency","isTest","photoUrl","formatCurrency","VENUE_COLORS","entries","arts_entertainment","building","education","event","food","home","nightlife","parks_outdoors","shops","travel","work","RANDOM_COLORS","variant","animation","classNames","MOVE_THRESHOLD","DEFAULT_MAP_CONFIG","zoom","SVG_PIN","__html","forceUpdate","useForceUpdate","getMessageLocation","geo","serverTime","isExpired","isGeoLiveExpired","secondsBeforeEnd","period","point","setPoint","shouldRenderText","buildStaticMapHash","prevMediaBlobUrl","mapBlobUrl","isPeerUser","avatarUser","avatarChat","accuracyRadiusPx","accuracyRadius","lat","cos","getMetersPerPixel","updateCountdown","timeLeft","formatCountdownShort","long","useTimeout","useInterval","prepareMapUrl","open","pinClassName","dangerouslySetInnerHTML","heading","str","prevHash","currVal","charCodeAt","getVenueColor","venueType","getVenueIconUrl","mapPin","renderPin","renderOverlay","address","formatLastUpdated","renderInfo","withSelectControl","WrappedComponent","ownProps","selectIsMessageSelected","handleMessageSelect","newProps","dims","PhotoWithSelect","Photo","VideoWithSelect","Video","activeDownloadIds","selectActiveDownloadIds","uploadsById","hasCustomAppendix","albumLayout","cancelSendingMessage","mediaCount","handleCancelUpload","containerWidth","containerHeight","fileUpload","selectCanAutoLoadMedia","selectCanAutoPlayMedia","stopPrevious","playingProgressRef","shouldSpinnerRender","setIsActivated","setProgress","svgCenter","ROUND_VIDEO_DIMENSIONS_PX","playerEl","playingProgressEl","stopPlaying","capturePlaying","stopCurrentAudio","videoClassName","recentReplierIds","recentRepliers","peerId","hasUnread","recentReactors","recentReaction","isOutside","metaChildren","localSticker","soundId","playKey","useAnimatedEmoji","localStickerAnimationData","setLocalStickerAnimationData","getAnimationData","quality","APPENDIX_OWN","APPENDIX_NOT_OWN","withSenderName","withAvatar","isLastInDocumentGroup","viaBotId","replyToChatId","isRepliesChat","isChatWithRepliesBot","chatUsername","forceSenderName","isAnonymousOwnMessage","canShowSender","originSender","botSender","threadTopMessageId","isThreadTop","shouldHideReply","replyMessageSender","selectUploadProgress","isForwarding","highlight","singleEmoji","getMessageSingleEmoji","selectIsDownloading","actualThreadInfo","selectIsMessageProtected","isSingleEmoji","animatedEmoji","selectAnimatedEmoji","animatedEmojiEffect","selectAnimatedEmojiEffect","animatedEmojiSoundId","selectAnimatedEmojiSound","isGroupSelected","selectIsDocumentGroupSelected","isPinnedList","canAutoLoadMedia","canAutoPlayMedia","autoLoadFileMaxSizeMb","shouldLoopStickers","selectShouldLoopStickers","selectOutgoingStatus","observeIntersectionForBottom","observeIntersectionForMedia","observeIntersectionForAnimatedStickers","areReactionsInMeta","noComments","isFirstInGroup","isLastInGroup","isFirstInDocumentGroup","clickInlineButton","bottomMarkerRef","isLocal","hasReply","isReplyMessage","hasThread","getMessageCustomShape","hasAnimatedEmoji","hasReactions","areReactionsEmpty","asForwarded","isLinkedChannelPost","isInDocumentGroupNotFirst","isInDocumentGroupNotLast","canShowActionButton","canForward","canFocus","isChannelPost","fromMessageId","withCommentButton","withQuickReactionButton","messageSender","avatarPeer","senderPeer","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","isGeoLiveActive","isMedia","isMediaWithNoText","isViaBot","isRound","buildContentClassName","withAppendix","textParts","renderMessageText","metaPosition","reactionsPosition","calculatedWidth","noMediaCorners","extraPadding","adminTitle","metaSafeAuthorWidth","renderReactionsAndMeta","meta","onMouseMove","isAvatarPeerUser","hiddenName","renderAvatar","textContentClass","senderColor","getUserColorKey","renderSenderName","AnimatedEmoji","effect","forceLoadPreview","Audio","AudioOrigin","isSelectable","onPlay","onReadMedia","Document","renderContent","isBot","channel","viewSponsoredMessage","openChatByInvite","startBot","shouldObserve","observe","useIntersectionObserver","rootRef","debounceMs","threshold","chatInviteTitle","chatInviteHash","messageGroups","isViewportNewest","withUsers","anchorIdRef","memoUnreadDividerBeforeIdRef","memoFirstUnreadIdRef","isScrollingRef","isScrollPatchNeededRef","hasLinkedChat","isSchedule","onFabToggle","onNotchToggle","openHistoryCalendar","observeIntersectionForReading","throttleMs","margin","freeze","freezeForReading","unfreeze","unfreezeForReading","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","useOnChange","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","noContextMenu","isGroupChatJustCreated","renderScheduled","renderSavedMessages","renderGroup","runDebouncedForScroll","selectCurrentMessageIds","restrictionReason","focusingId","withLastMessageWhenPreloading","chatBot","botDescription","isChatLoaded","isChannelChat","isGroupChat","isChatGroup","threadFirstMessageId","selectFirstMessageId","linkedChatId","hasTools","canPost","withBottomShift","setScrollOffset","loadSponsoredMessages","loadMessageReactions","copyMessagesByIds","scrollOffsetRef","selectScrollOffset","anchorTopRef","listItemElementsRef","memoFocusingIdRef","isScrollTopJustUpdatedRef","shouldAnimateAppearanceRef","setContainerHeight","onTickEnd","handleCopy","getMessageIdsForSelectedText","useNativeCopySelectedMessages","listedMessages","orderBy","loadMoreAround","isScrolled","updateStickyDates","markIsScrolled","runDebounced","useDebounce","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","backgroundColor","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","insertHtmlInSelection","html","selection","getSelection","getRangeAt","rangeCount","range","deleteContents","fragment","createContextualFragment","lastInsertedNode","lastChild","insertNode","setStartAfter","setEndAfter","collapse","removeAllRanges","addRange","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","useDebouncedMemo","resolverFn","ms","dependencies","setValue","isFrozen","INLINE_BOT_QUERY_REGEXP","HAS_NEW_LINE","MEMO_NO_RESULT","canShowHelp","usernameLowered","tempEl","runThrottled","RE_COMMAND","DeleteMessageModal","openTimeout","isFirstTimeActivation","onActivate","buttonProps","isButtonVisible","canAttachMedia","canAttachPolls","onFileSelect","onPollCreate","isAttachMenuOpen","openAttachMenu","closeAttachMenu","markMouseInside","useMouseInside","handleFileSelect","files","handleQuickSelect","openSystemFilesDialog","CONTENT_TYPES_WITH_PREVIEW","handleDocumentSelect","ariaControls","hasPopup","noCloseOnBackdrop","ariaLabelledBy","SymbolMenu","InlineBotTooltip","MentionTooltip","StickerTooltip","BotCommandTooltip","isKeyboardSingleUse","forceOpen","markForceOpen","unmarkForceOpen","keyboardButtons","noCompact","forwardMessageIds","forwardedMessagesCount","onClear","exitForwardMode","canAnimate","useAsyncRendering","clearEmbedded","handleMessageClick","faded","AttachmentModal","BotCommandMenu","PollModal","DropArea","RE_LINK","RegExp","RE_LINK_TEMPLATE","messageText","toggleMessageWebPage","linkEntity","ApiMessageEntityTypes","textMatch","renderingWebPage","webPageWithoutPhoto","messageStub","SendAsMenu","MainButtonState","VOICE_RECORDING_FILENAME","REPLIES_USER_ID","messageWithActualBotKeyboard","selectNewestMessageWithBotKeyboardButtons","shouldSuggestStickers","baseEmojiKeywords","BASE_EMOJI_KEYWORD_LANG","botKeyboardMessageId","keyboardMessage","defaultSendAsId","anonymous","sendAsUser","selectEditingScheduledDraft","editingMessage","canScheduleUntilOnline","selectCanScheduleUntilOnline","withScheduledButton","shouldSchedule","botKeyboardPlaceholder","keyboardPlaceholder","stickersForEmoji","groupChatMembers","topInlineBotIds","isInlineBotLoading","chatBotCommands","botCommands","dropAreaState","onDropHide","clearDraft","setStickerSearchQuery","setGifSearchQuery","closePollModal","addRecentEmoji","sendInlineBotResult","loadSendAs","appendixRef","setHtml","htmlRef","useStateRef","lastMessageSendTimeSeconds","prevDropAreaState","canShowSendAs","isSymbolMenuForced","forceShowSymbolMenu","cancelForceShowSymbolMenu","sendMessageAction","useSendMessageAction","handleScheduleCancel","requestCalendar","calendar","useSchedule","shouldAnimateSendAsButtonRef","prevChatId","prevSendAsIds","setAttachments","isBotKeyboardOpen","openBotKeyboard","closeBotKeyboard","isBotCommandMenuOpen","openBotCommandMenu","closeBotCommandMenu","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","SEND_MESSAGE_ACTION_INTERVAL","mainButtonState","Edit","Schedule","Send","Record","canShowCustomSendMenu","isMentionTooltipOpen","closeMentionTooltip","insertMention","mentionFilteredUsers","useMentionTooltip","isInlineBotTooltipOpen","inlineBotId","isInlineBotTooltipGallery","inlineBotSwitchPm","inlineBotResults","closeTooltip","closeInlineBotTooltip","inlineBotHelp","loadMore","loadMoreForInlineBot","queryInlineBot","resetInlineBot","markIsOpen","unmarkIsOpen","innerText","getPlainText","parseBotQuery","prevQuery","prevUsername","useInlineBotTooltip","isBotCommandTooltipOpen","close","closeBotCommandTooltip","filteredBotCommands","botTooltipCommands","setFilteredBotCommands","getFilteredCommands","nextFilteredBotCommands","prepareForRegExp","substr","useBotCommandTooltip","isCustomSendMenuOpen","canSendStickers","canSendGifs","canAttachEmbedLinks","getAllowedAttachmentOptions","isChatAdmin","slowMode","getChatSlowModeOptions","isStickerTooltipOpen","closeStickerTooltip","cleanHtml","trim","clearStickersForEmoji","IS_EMOJI_SUPPORTED","parseEmojiOnlyString","hasStickers","useStickerTooltip","isEmojiTooltipOpen","closeEmojiTooltip","filteredEmojis","insertEmoji","useEmojiTooltip","insertTextAndUpdateCursor","newHtml","selectionRange","isSelectionInsideInput","dispatchEvent","Event","bubbles","focusEditableElement","removeSymbol","execCommand","tempInput","contentEditable","textLength","createRange","setStart","setEnd","removeChild","deleteLastCharacterOutsideSelection","resetComposer","shouldPreserveInput","stopRecordingVoiceRef","handleEditComplete","handleEditCancel","editedMessage","editMessage","setEditingDraft","prevEditedMessage","getTextWithEntitiesAsHtml","edited","restoreNewDraftAfterEditing","hasMessageMedia","handleBlur","useEditing","saveDraft","updateDraft","draftChatId","draftThreadId","currentHtml","runDebouncedForSaveDraft","DRAFT_DEBOUNCE","prevThreadId","prevHtml","useDraft","handlePaste","clipboardData","input","activeElement","EDITABLE_INPUT_MODAL_ID","pastedText","getData","substring","items","getFilesFromDataTransferItems","newAttachments","all","file","useClipboardPaste","handleEmbeddedClear","handleAppendFiles","handleClearAttachment","handleSend","currentAttachments","record","maxLength","extraLength","textParams","nowSeconds","secondsSinceLastMessage","nextSendDateNotReached","nextSendDate","seconds","secondsRemaining","isSlowMode","handleActivateBotCommandMenu","handleActivateSymbolMenu","handleMessageSchedule","args","restArgs","isScheduleRequested","handleGifSelect","handleInlineBotSelect","inlineResult","handleBotCommandSelect","handlePollSend","handleSendSilent","handleSearchOpen","handleSymbolMenuOpen","handleSendAsMenuOpen","handleAllScheduledClick","mainButtonHandler","areVoiceMessagesNotAllowed","renderedEditedMessage","scheduledDefaultDate","setSeconds","setMilliseconds","scheduledMaxDate","setFullYear","getFullYear","sendButtonAriaLabel","symbolMenuButtonClassName","handleSendScheduled","onSend","DropAreaState","withQuick","onHide","caption","onCaptionUpdate","onSendSilent","onSendScheduled","onFileAppend","shouldBeAnonimous","selectedSendAsId","onInsertUserName","filteredUsers","onSelectResult","isSavedMessages","withUsername","MessageInput","forcedPlaceholder","canAutoFocus","shouldSuppressFocus","shouldSuppressTextFormatter","onUpdate","onSuppressedFocus","formatVoiceRecordDuration","onStickerSelect","emojis","onEmojiSelect","onGifSelect","onRemoveSymbol","onSearchOpen","onSendSchedule","MobileSearch","MessageSelectToolbar","UnpinAllMessagesModal","PaymentModal","ReceiptModal","SeenByModal","EmojiInteractionAnimation","ReactorListModal","CLOSE_ANIMATION_DURATION","isImage","kind","isBlurred","isBackgroundBlurred","background","customBackground","patternColor","themes","isMobileSearchActive","isReceiptModalOpen","isSeenByModalOpen","isReactorListModalOpen","getCanPostInChat","isBotNotStarted","isPinnedMessageList","isScheduledMessageList","areChatSettingsLoaded","currentUserBannedRights","defaultBannedRights","hasPinnedOrAudioPlayer","loadUser","loadChatSettings","closePaymentModal","clearReceipt","setDropAreaState","isFabShown","setIsFabShown","isNotchShown","setIsNotchShown","isUnpinModalOpen","setIsUnpinModalOpen","renderingChatId","usePrevDuringAnimation","renderingThreadId","renderingMessageListType","renderingCanSubscribe","renderingCanStartBot","renderingCanRestartBot","renderingCanPost","renderingHasTools","renderingIsFabShown","renderingIsChannel","prevTransitionKey","handleOpenEnd","handleSlideStop","withAnimations","setIsReady","willSwitchMessageList","propertyName","useIsReady","ANIMATION_LEVEL_MIN","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","teactOrderKey","HeaderContent","isProfile","isManagement","messageSearchQuery","stickerSearchQuery","selectCurrentStickerSearch","gifSearchQuery","selectCurrentGifSearch","getCanAddContact","canManage","isEditingInvite","isColumnOpen","isSearch","isStatistics","isStickerSearch","isGifSearch","isPollResults","isAddingChatMembers","profileState","managementScreen","shouldSkipAnimation","setLocalTextSearchQuery","searchTextMessagesLocal","toggleManagement","toggleStatistics","setEditingExportedInvite","deleteExportedChatInvite","backButtonRef","isDeleteDialogOpen","openDeleteDialog","closeDeleteDialog","handleEditInviteClick","handleDeleteInviteClick","handleMessageSearchQueryChange","handleStickerSearchQueryChange","handleGifSearchQueryChange","setShouldSkipTransition","contentKey","ProfileState","Profile","SharedMedia","MemberList","Search","PollResults","StickerSearch","GifSearch","AddingMembers","ManageInitial","ManageChatPrivacyType","ManageDiscussion","ManageChannelSubscribers","ManageGroupPermissions","ManageChatAdministrators","ManageGroupRemovedUsers","ManageChannelRemovedUsers","ManageGroupUserPermissionsCreate","ManageGroupUserPermissions","ManageGroupRecentActions","ManageGroupAdminRights","ManageGroupNewAdminRights","ManageGroupMembers","ManageInvites","ManageEditInvite","ManageGroupAddAdmins","ManageReactions","ManageInviteInfo","ManageJoinRequests","Statistics","renderingContentKey","isBackButton","buttonClassName","autoFocusSearch","renderHeaderContent","useInfiniteScrollForLoadableItems","currentResultType","handleLoadMore","itemIds","getMore","useInfiniteScroll","MEMBERS_SLICE","useInfiniteScrollForSharedMedia","forSharedMediaType","messageIdsRef","getMessageContentIds","runThrottledForScroll","isScrollingProgrammatically","TABS","buildInfiniteScrollItemSelector","resultType","mediaSearchType","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","canRenderContent","InfiniteScroll","itemSelector","sensitiveArea","PROFILE_SENSITIVE_AREA","preloadBackwards","noScrollRestoreOnTop","noFastList","onLoadMore","ProfileInfo","ChatExtra","renderProfileInfo","shouldRestoreHeight","onStart","noSpinner","NothingFound","Media","withDate","smaller","onDateClick","WebLink","onMessageClick","getSenderName","ListItem","contextActions","memberId","handler","forceShowSelf","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","nextManagementScreen","selectRightColumnContentKey","isChatSelected","toggleChatInfo","closePollResults","addChatMembers","setOpenedInviteInfo","setProfileState","setManagementScreen","selectedChatMemberId","setSelectedChatMemberId","isPromotedByCurrentUser","setIsPromotedByCurrentUser","isScrolledDown","isOverlaying","shouldScrollUp","handleSelectChatMember","isPromoted","handleAppendingChatMembers","onChatMemberSelect","MediaViewer","download","click","startedDownloads","downloadHash","getMessageContentFilename","Notifications","Dialogs","ForwardPicker","SafeLinkModal","HistoryCalendar","GroupCall","ActiveCallHeader","CallFallbackConfirm","NewContactModal","notificationInterval","DEBUG_isLogged","updateIcon","asUnread","updatePageTitle","nextTitle","wasTimeFormatSetManually","authState","isMediaViewerOpen","selectIsMediaViewerOpen","isForwardModalOpen","selectIsForwardModalOpen","hasNotifications","hasDialogs","isHistoryCalendarOpen","isServiceChatReady","isCallFallbackConfirmOpen","isFallbackConfirmOpen","newContactUserId","newContactByPhoneNumber","sync","loadNotificationSettings","loadNotificationExceptions","updateIsOnline","loadTopInlineBots","loadEmojiKeywords","loadCountryList","loadAvailableReactions","loadAddedStickers","ensureTimeFormat","openStickerSetShortName","checkVersionNotification","loadAppConfig","LOCATION_HASH","processDeepLink","decodeURIComponent","middleColumnTransitionClassNames","rightColumnTransitionClassNames","prevIsLeftColumnShown","dispatchHeavyAnimationEnd","waitForTransitionEnd","prevIsRightColumnShown","initialUnread","setInterval","INACTIVE_MARKER","newUnread","PAGE_TITLE","handleStickerSetModalClose","usePreventPinchZoomGesture","onDrop","onDragOver","initApi"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"616.421a1d053cdd90ce3d23.js","mappings":"gOAoDO,SAASA,EAAqBC,GACnC,MAAM,OAAEC,EAAF,SAAUC,IAAaC,EAAAA,EAAAA,IAAyBH,IAAW,GACjE,OAAKC,GAAWC,GAIhBF,GAASI,EAAAA,EAAAA,IAAsBJ,EAAQC,EAAQC,GAAU,GACzDF,GAASK,EAAAA,EAAAA,IAA8BL,EAAQC,EAAQC,OAAUI,IAJxDN,GA3CXO,EAAAA,EAAAA,IAAiB,uBAAwBP,IACvC,MAAM,OAAEC,EAAF,SAAUC,IAAaC,EAAAA,EAAAA,IAAyBH,IAAW,GACjE,GAAKC,GAAWC,EAIhB,OAAOE,EAAAA,EAAAA,IAAsBJ,EAAQC,EAAQC,GAAU,OAGzDK,EAAAA,EAAAA,IAAiB,uBAAwBR,IAEzCQ,EAAAA,EAAAA,IAAiB,2BAA2B,CAACP,EAAQQ,EAASC,KAC5D,MAAM,OAAER,EAAF,SAAUC,IAAaC,EAAAA,EAAAA,IAAyBH,IAAW,GACjE,IAAKC,IAAWC,EACd,OAGF,MAAM,MAAEQ,GAAUD,EACZE,GAAgBC,EAAAA,EAAAA,IAAmBX,EAAQC,IACzCQ,MAAOG,GAAiBb,EAAOc,gBAAgBC,gBAAgBJ,IAAkB,GAQzF,OANID,IAAUG,IACZb,GAASK,EAAAA,EAAAA,IAA8BL,EAAQC,EAAQC,EAAUc,EAAAA,KAG1DZ,EAAAA,EAAAA,IAAsBJ,EAAQC,EAAQC,GAAU,EAAMQ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BAAC,GAAD,CAAa/tB,OAAQuvE,IACrB,mBAAC,GAAD,CAAevvE,OAAQyvE,IACvB,mBAAC,GAAD,CAAezvE,OAAQ2vE,IACvB,mBAAC,GAAD,CAAS3vE,OAAQ4vE,IAChBzxD,GAAgB,mBAAC,GAAD,CAAa9kB,IAAK8kB,EAAax/C,GAAIoC,QAASo9C,EAAcpF,MAAI,IAC/E,mBAAC,GAAD,CAAe1sC,IAAKC,IACpB,mBAAC,GAAD,CAAiB0zB,OAAQ6vE,IACzB,mBAAC,KAAD,CACE7vE,OAAQ19B,QAAQwY,GAChBusB,QAASyqE,EACTl5F,oBAAqBkC,IAEtBkf,GACC,sCACE,mBAAC,GAAD,CAAWM,YAAaN,IACxB,mBAAC,GAAD,CAAkBM,YAAaN,KAGnC,mBAAC,GAAD,CACEgG,OAAQ19B,QAAQ2tG,GAAoBC,GACpCpmG,OAAQmmG,EACRjmG,gBAAiBkmG,IAEnB,mBAAC,GAAD,MACA,mBAAC,GAAD,CAAqBlwE,OAAQ+vE,IAC7B,mBAAC,GAAD,CAAaz0E,eAAa,SCjV5Bzb,EAAAA,IAEFC,QAAQC,IAAI,gCAGT3b,EAAAA,EAAAA,MAAY01B,kBACf1c,EAAAA,EAAAA,MAAa80F,W","sources":["webpack://telegram-t/./src/global/actions/ui/localSearch.ts","webpack://telegram-t/./src/global/actions/ui/chats.ts","webpack://telegram-t/./src/global/actions/ui/messages.ts","webpack://telegram-t/./src/global/actions/ui/globalSearch.ts","webpack://telegram-t/./src/global/actions/ui/stickerSearch.ts","webpack://telegram-t/./src/global/actions/ui/users.ts","webpack://telegram-t/./src/global/actions/ui/misc.ts","webpack://telegram-t/./src/global/actions/ui/payments.ts","webpack://telegram-t/./src/global/actions/ui/mediaViewer.ts","webpack://telegram-t/./src/global/actions/api/messages.ts","webpack://telegram-t/./src/global/actions/api/symbols.ts","webpack://telegram-t/./src/global/actions/api/globalSearch.ts","webpack://telegram-t/./src/global/actions/api/localSearch.ts","webpack://telegram-t/./src/global/actions/api/management.ts","webpack://telegram-t/./src/global/actions/api/sync.ts","webpack://telegram-t/./src/global/actions/api/users.ts","webpack://telegram-t/./src/global/reducers/bots.ts","webpack://telegram-t/./src/global/actions/api/bots.ts","webpack://telegram-t/./src/global/actions/api/twoFaSettings.ts","webpack://telegram-t/./src/global/actions/api/payments.ts","webpack://telegram-t/./src/util/requestQuery.ts","webpack://telegram-t/./src/components/middle/helpers/calculateMiddleFooterTransforms.ts","webpack://telegram-t/./src/global/reducers/reactions.ts","webpack://telegram-t/./src/global/actions/api/reactions.ts","webpack://telegram-t/./src/global/actions/api/statistics.ts","webpack://telegram-t/./src/util/areDeepEqual.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/chats.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/messages.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/users.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/symbols.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/misc.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/settings.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/twoFaSettings.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/calls.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/payments.ts","webpack://telegram-t/./src/hooks/useBeforeUnload.ts","webpack://telegram-t/./src/hooks/usePreventPinchZoomGesture.ts","webpack://telegram-t/./src/components/common/UnreadCounter.tsx","webpack://telegram-t/./src/hooks/useConnectionStatus.ts","webpack://telegram-t/./src/hooks/useBrowserOnline.ts","webpack://telegram-t/./src/components/left/ConnectionStatusOverlay.tsx","webpack://telegram-t/./src/components/left/main/LeftMainHeader.tsx","webpack://telegram-t/./src/components/left/main/ChatFolders.tsx","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/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/ChatReportPanel.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/hooks/useOuterHandlers.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/ReactionAnimatedEmoji.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/util/map.ts","webpack://telegram-t/./src/components/ui/Skeleton.tsx","webpack://telegram-t/./src/components/middle/message/Location.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/ReactionButton.tsx","webpack://telegram-t/./src/components/middle/message/Reactions.tsx","webpack://telegram-t/./src/components/common/LocalAnimatedEmoji.tsx","webpack://telegram-t/./src/components/middle/message/Message.tsx","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/hooks/useNativeCopySelectedMessages.ts","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/util/insertHtmlInSelection.ts","webpack://telegram-t/./src/components/middle/composer/helpers/applyIosAutoCapitalizationFix.ts","webpack://telegram-t/./src/util/voiceRecording.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useClipboardPaste.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useDraft.ts","webpack://telegram-t/./src/hooks/useDebouncedMemo.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.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/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/middle/composer/SendAsMenu.async.tsx","webpack://telegram-t/./src/components/middle/composer/Composer.tsx","webpack://telegram-t/./src/components/middle/composer/hooks/useVoiceRecording.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useStickerTooltip.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/EmojiInteractionAnimation.async.tsx","webpack://telegram-t/./src/components/middle/ReactorListModal.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/statistics/Statistics.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/NewContactModal.async.tsx","webpack://telegram-t/./src/components/main/Main.tsx","webpack://telegram-t/./src/bundles/main.ts"],"sourcesContent":["import { addActionHandler } from '../../index';\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 '../../types';\n\naddActionHandler('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\naddActionHandler('closeLocalTextSearch', closeLocalTextSearch);\n\naddActionHandler('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\naddActionHandler('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 { addActionHandler, setGlobal } from '../../index';\n\nimport { MAIN_THREAD_ID } from '../../../api/types';\n\nimport {\n exitMessageSelectMode, replaceThreadParam, updateCurrentMessageList,\n} from '../../reducers';\nimport { selectCurrentMessageList } from '../../selectors';\nimport { closeLocalTextSearch } from './localSearch';\n\naddActionHandler('openChat', (global, actions, payload) => {\n const {\n id,\n threadId = MAIN_THREAD_ID,\n type = 'thread',\n 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 if (id) {\n global = replaceThreadParam(global, id, threadId, 'replyStack', []);\n }\n\n global = exitMessageSelectMode(global);\n global = closeLocalTextSearch(global);\n\n global = {\n ...global,\n isStatisticsShown: false,\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\naddActionHandler('openPreviousChat', (global) => {\n return updateCurrentMessageList(global, undefined);\n});\n\naddActionHandler('openChatWithInfo', (global, actions, payload) => {\n setGlobal({\n ...global,\n isChatInfoShown: true,\n });\n\n actions.openChat(payload);\n});\n\naddActionHandler('resetChatCreation', (global) => {\n return {\n ...global,\n chatCreation: undefined,\n };\n});\n\naddActionHandler('setNewChatMembersDialogState', (global, actions, payload) => {\n return {\n ...global,\n newChatMembersProgress: payload,\n };\n});\n\naddActionHandler('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 { addActionHandler, getGlobal, setGlobal } from '../../index';\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 selectSender,\n} from '../../selectors';\nimport { findLast } from '../../../util/iteratees';\nimport { getServerTime } from '../../../util/serverTime';\n\nimport versionNotification from '../../../versionNotification.txt';\nimport parseMessageInput from '../../../util/parseMessageInput';\nimport { getMessageSummaryText, getSenderTitle } from '../../helpers';\nimport * as langProvider from '../../../util/langProvider';\nimport { copyTextToClipboard } from '../../../util/clipboard';\nimport { GlobalState } from '../../types';\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\naddActionHandler('setScrollOffset', (global, actions, payload) => {\n const { chatId, threadId, scrollOffset } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'scrollOffset', scrollOffset);\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('setEditingDraft', (global, actions, payload) => {\n const {\n text, chatId, threadId, type,\n } = payload;\n\n const paramName = type === 'scheduled' ? 'editingScheduledDraft' : 'editingDraft';\n\n return replaceThreadParam(global, chatId, threadId, paramName, text);\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('openPollResults', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n\n const shouldOpenInstantly = selectIsRightColumnShown(global);\n\n if (!shouldOpenInstantly) {\n window.setTimeout(() => {\n global = getGlobal();\n\n setGlobal({\n ...global,\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 return {\n ...global,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n };\n }\n\n return undefined;\n});\n\naddActionHandler('closePollResults', (global) => {\n return {\n ...global,\n pollResults: {},\n };\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('exitForwardMode', (global) => {\n setGlobal({\n ...global,\n forwardMessages: {},\n });\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('disableContextMenuHint', (global) => {\n if (!global.shouldShowContextMenuHint) {\n return undefined;\n }\n\n return {\n ...global,\n shouldShowContextMenuHint: false,\n };\n});\n\naddActionHandler('exitMessageSelectMode', exitMessageSelectMode);\n\naddActionHandler('openPollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: true,\n };\n});\n\naddActionHandler('closePollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: false,\n };\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('openReactorListModal', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n\n return {\n ...global,\n reactorModal: { chatId, messageId },\n };\n});\n\naddActionHandler('closeReactorListModal', (global) => {\n return {\n ...global,\n reactorModal: undefined,\n };\n});\n\naddActionHandler('openSeenByModal', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n\n return {\n ...global,\n seenByModal: { chatId, messageId },\n };\n});\n\naddActionHandler('closeSeenByModal', (global) => {\n return {\n ...global,\n seenByModal: undefined,\n };\n});\n\naddActionHandler('copySelectedMessages', (global) => {\n if (!global.selectedMessages) {\n return;\n }\n\n const { chatId, messageIds } = global.selectedMessages;\n copyTextForMessages(global, chatId, messageIds);\n});\n\naddActionHandler('copyMessagesByIds', (global, actions, payload: { messageIds?: number[] }) => {\n const { messageIds } = payload;\n const chat = selectCurrentChat(global);\n if (!messageIds || messageIds.length === 0 || !chat) {\n return;\n }\n\n copyTextForMessages(global, chat.id, messageIds);\n});\n\nfunction copyTextForMessages(global: GlobalState, chatId: string, messageIds: number[]) {\n const { threadId } = selectCurrentMessageList(global) || {};\n const lang = langProvider.getTranslation;\n\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages || !threadId) return;\n const messages = messageIds\n .map((id) => chatMessages[id])\n .filter((message) => selectAllowedMessageActions(global, message, threadId).canCopy)\n .sort((message1, message2) => message1.id - message2.id);\n\n const result = messages.reduce((acc, message) => {\n const sender = selectSender(global, message);\n acc.push(`> ${sender ? getSenderTitle(lang, sender) : ''}:`);\n acc.push(`${getMessageSummaryText(lang, message, false, 0, undefined, true)}\\n`);\n\n return acc;\n }, [] as string[]);\n\n copyTextToClipboard(result.join('\\n'));\n}\n","import { addActionHandler } from '../../index';\n\nimport { updateGlobalSearch, updateGlobalSearchContent } from '../../reducers';\n\nconst MAX_RECENTLY_FOUND_IDS = 10;\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('clearRecentlyFoundChats', (global) => {\n return updateGlobalSearch(global, { recentlyFoundChatIds: undefined });\n});\n\naddActionHandler('setGlobalSearchContent', (global, actions, payload) => {\n const { content } = payload!;\n\n return updateGlobalSearchContent(global, content);\n});\n\naddActionHandler('setGlobalSearchChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n return updateGlobalSearch(global, { chatId: id, query: undefined, resultsByType: undefined });\n});\n","import { addActionHandler } from '../../index';\n\naddActionHandler('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\naddActionHandler('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 { addActionHandler } from '../../index';\n\nimport { closeNewContactDialog, updateUserSearch } from '../../reducers';\n\naddActionHandler('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\naddActionHandler('openAddContactDialog', (global, actions, payload) => {\n const { userId } = payload!;\n\n return {\n ...global,\n newContact: { userId },\n };\n});\n\naddActionHandler('openNewContactDialog', (global) => {\n return {\n ...global,\n newContact: {\n isByPhoneNumber: true,\n },\n };\n});\n\naddActionHandler('closeNewContactDialog', (global) => {\n return closeNewContactDialog(global);\n});\n","import { addActionHandler } from '../../index';\n\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\naddActionHandler('toggleChatInfo', (global, action, payload) => {\n return {\n ...global,\n isChatInfoShown: payload !== undefined ? payload : !global.isChatInfoShown,\n };\n});\n\naddActionHandler('setLeftColumnWidth', (global, actions, payload) => {\n const leftColumnWidth = payload;\n\n return {\n ...global,\n leftColumnWidth,\n };\n});\n\naddActionHandler('resetLeftColumnWidth', (global) => {\n return {\n ...global,\n leftColumnWidth: undefined,\n };\n});\n\naddActionHandler('toggleManagement', (global) => {\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\naddActionHandler('requestNextManagementScreen', (global, actions, payload) => {\n const { screen } = payload || {};\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: true,\n nextScreen: screen,\n },\n },\n },\n };\n});\n\naddActionHandler('closeManagement', (global) => {\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\naddActionHandler('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\naddActionHandler('toggleStatistics', (global) => {\n return {\n ...global,\n isStatisticsShown: !global.isStatisticsShown,\n };\n});\n\naddActionHandler('toggleLeftColumn', (global) => {\n return {\n ...global,\n isLeftColumnShown: !global.isLeftColumnShown,\n };\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('dismissDialog', (global) => {\n const newDialogs = [...global.dialogs];\n\n newDialogs.pop();\n\n return {\n ...global,\n dialogs: newDialogs,\n };\n});\n\naddActionHandler('toggleSafeLinkModal', (global, actions, payload) => {\n const { url: safeLinkModalUrl } = payload;\n\n return {\n ...global,\n safeLinkModalUrl,\n };\n});\n\naddActionHandler('openHistoryCalendar', (global, actions, payload) => {\n const { selectedAt } = payload;\n\n return {\n ...global,\n historyCalendarSelectedAt: selectedAt,\n };\n});\n\naddActionHandler('closeHistoryCalendar', (global) => {\n return {\n ...global,\n historyCalendarSelectedAt: undefined,\n };\n});\n","import { addActionHandler } from '../../index';\n\nimport { clearPayment, closeInvoice } from '../../reducers';\n\naddActionHandler('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\naddActionHandler('closePaymentModal', (global) => {\n global = clearPayment(global);\n global = closeInvoice(global);\n return global;\n});\n\naddActionHandler('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 { addActionHandler } from '../../index';\n\naddActionHandler('openMediaViewer', (global, actions, payload) => {\n const {\n chatId, threadId, messageId, avatarOwnerId, profilePhotoIndex, origin, volume, playbackRate, isMuted,\n } = payload;\n\n return {\n ...global,\n mediaViewer: {\n ...global.mediaViewer,\n chatId,\n threadId,\n messageId,\n avatarOwnerId,\n profilePhotoIndex,\n origin,\n volume: volume ?? global.mediaViewer.volume,\n playbackRate: playbackRate || global.mediaViewer.playbackRate,\n isMuted: isMuted || global.mediaViewer.isMuted,\n },\n forwardMessages: {},\n };\n});\n\naddActionHandler('closeMediaViewer', (global) => {\n const { volume, isMuted, playbackRate } = global.mediaViewer;\n return {\n ...global,\n mediaViewer: {\n volume,\n isMuted,\n playbackRate,\n },\n };\n});\n\naddActionHandler('setMediaViewerVolume', (global, actions, payload) => {\n const {\n volume,\n } = payload;\n\n return {\n ...global,\n mediaViewer: {\n ...global.mediaViewer,\n volume,\n },\n };\n});\n\naddActionHandler('setMediaViewerPlaybackRate', (global, actions, payload) => {\n const {\n playbackRate,\n } = payload;\n\n return {\n ...global,\n mediaViewer: {\n ...global.mediaViewer,\n playbackRate,\n },\n };\n});\n\naddActionHandler('setMediaViewerMuted', (global, actions, payload) => {\n const {\n isMuted,\n } = payload;\n\n return {\n ...global,\n mediaViewer: {\n ...global.mediaViewer,\n isMuted,\n },\n };\n});\n","import { addActionHandler, getGlobal, setGlobal } from '../../index';\n\nimport { GlobalActions } from '../../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 {\n MAX_MEDIA_FILES_FOR_ALBUM,\n MESSAGE_LIST_SLICE,\n SERVICE_NOTIFICATIONS_USER_ID,\n} 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\naddActionHandler('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\naddActionHandler('loadMessage', async (global, actions, payload) => {\n const {\n chatId, messageId, replyOriginForId, threadUpdate,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n const message = await loadMessage(chat, messageId, replyOriginForId);\n if (message && threadUpdate) {\n const { lastMessageId, isDeleting } = threadUpdate;\n\n return updateThreadUnreadFromForwardedMessage(\n getGlobal(),\n message,\n chatId,\n lastMessageId,\n isDeleting,\n );\n }\n\n return undefined;\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('toggleMessageWebPage', (global, actions, payload) => {\n const { chatId, threadId, noWebPage } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'noWebPage', noWebPage);\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('deleteHistory', async (global, actions, payload) => {\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\naddActionHandler('reportMessages', async (global, actions, payload) => {\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\naddActionHandler('sendMessageAction', async (global, actions, payload) => {\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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('loadWebPagePreview', (global, actions, payload) => {\n const { text } = payload!;\n void loadWebPagePreview(text);\n});\n\naddActionHandler('clearWebPagePreview', (global) => {\n if (!global.webPagePreview) {\n return undefined;\n }\n\n return {\n ...global,\n webPagePreview: undefined,\n };\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('loadSeenBy', async (global, actions, payload) => {\n const { chatId, messageId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n const result = await callApi('fetchSeenBy', { chat, messageId });\n if (!result) {\n return undefined;\n }\n\n return updateChatMessage(getGlobal(), chatId, messageId, {\n seenByUserIds: result,\n });\n});\n\naddActionHandler('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\naddActionHandler('loadSendAs', async (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n const result = await callApi('fetchSendAs', { chat });\n if (!result) {\n return updateChat(getGlobal(), chatId, {\n sendAsIds: [],\n });\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, { sendAsIds: result.ids });\n return global;\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\naddActionHandler('loadSponsoredMessages', async (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n const result = await callApi('fetchSponsoredMessages', { chat });\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n global = updateSponsoredMessage(global, chatId, result.messages[0]);\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n global = addChats(global, buildCollectionByKey(result.chats, 'id'));\n return global;\n});\n\naddActionHandler('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 { addActionHandler, getGlobal, setGlobal } from '../../index';\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\naddActionHandler('loadStickerSets', (global) => {\n const { hash } = global.stickers.added || {};\n void loadStickerSets(hash);\n});\n\naddActionHandler('loadAddedStickers', async (global, actions) => {\n const { setIds: addedSetIds } = global.stickers.added;\n const cached = global.stickers.setsById;\n if (!addedSetIds || !addedSetIds.length) {\n return;\n }\n\n for (let i = 0; i < addedSetIds.length; i++) {\n const id = addedSetIds[i];\n if (cached[id].stickers) {\n continue; // Already loaded\n }\n actions.loadStickers({ stickerSetId: id });\n\n if (i % ADDED_SETS_THROTTLE_CHUNK === 0 && i > 0) {\n await pause(ADDED_SETS_THROTTLE);\n }\n }\n});\n\naddActionHandler('loadRecentStickers', (global) => {\n const { hash } = global.stickers.recent || {};\n void loadRecentStickers(hash);\n});\n\naddActionHandler('loadFavoriteStickers', (global) => {\n const { hash } = global.stickers.favorite || {};\n void loadFavoriteStickers(hash);\n});\n\naddActionHandler('loadGreetingStickers', async (global) => {\n const { hash } = global.stickers.greeting || {};\n\n const greeting = await callApi('fetchStickersForEmoji', { emoji: '👋⭐️', hash });\n if (!greeting) {\n return undefined;\n }\n\n global = getGlobal();\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n greeting: {\n hash: greeting.hash,\n stickers: greeting.stickers.filter((sticker) => sticker.emoji === '👋'),\n },\n },\n };\n});\n\naddActionHandler('loadFeaturedStickers', (global) => {\n const { hash } = global.stickers.featured || {};\n void loadFeaturedStickers(hash);\n});\n\naddActionHandler('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\naddActionHandler('loadAnimatedEmojis', () => {\n void loadAnimatedEmojis();\n void loadAnimatedEmojiEffects();\n});\n\naddActionHandler('loadSavedGifs', (global) => {\n const { hash } = global.gifs.saved;\n void loadSavedGifs(hash);\n});\n\naddActionHandler('saveGif', async (global, actions, payload) => {\n const { gif, shouldUnsave } = payload!;\n const result = await callApi('saveGif', { gif, shouldUnsave });\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n const gifs = global.gifs.saved.gifs?.filter(({ id }) => id !== gif.id) || [];\n const newGifs = shouldUnsave ? gifs : [gif, ...gifs];\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n saved: {\n ...global.gifs.saved,\n gifs: newGifs,\n },\n },\n };\n});\n\naddActionHandler('faveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void callApi('faveSticker', { sticker });\n }\n});\n\naddActionHandler('unfaveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void unfaveSticker(sticker);\n }\n});\n\naddActionHandler('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\naddActionHandler('loadEmojiKeywords', async (global, actions, payload: { language: LangCode }) => {\n const { language } = payload;\n\n let currentEmojiKeywords = global.emojiKeywords[language];\n if (currentEmojiKeywords?.isLoading) {\n return undefined;\n }\n\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n ...currentEmojiKeywords,\n isLoading: true,\n },\n },\n });\n\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 return {\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n ...currentEmojiKeywords,\n isLoading: false,\n },\n },\n };\n }\n\n return {\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\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\nasync function loadAnimatedEmojiEffects() {\n const stickerSet = await callApi('fetchAnimatedEmojiEffects');\n if (!stickerSet) {\n return;\n }\n\n const { set, stickers } = stickerSet;\n\n setGlobal({\n ...getGlobal(),\n animatedEmojiEffects: { ...set, stickers },\n });\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\naddActionHandler('setStickerSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (query) {\n void searchThrottled(() => {\n searchStickers(query);\n });\n }\n});\n\naddActionHandler('setGifSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (typeof query === 'string') {\n void searchThrottled(() => {\n searchGifs(query);\n });\n }\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('clearStickersForEmoji', (global) => {\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {},\n },\n };\n});\n\naddActionHandler('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 { addActionHandler, getGlobal, setGlobal } from '../../index';\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\naddActionHandler('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\naddActionHandler('setGlobalSearchDate', (global, actions, payload) => {\n const { date } = payload!;\n const maxDate = date ? timestampPlusDay(date) : date;\n\n global = 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(global);\n\n const { chatId } = global.globalSearch;\n const chat = chatId ? selectChat(global, chatId) : undefined;\n searchMessagesGlobal('', 'text', undefined, chat, maxDate, date);\n});\n\naddActionHandler('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 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 addActionHandler, getActions, getGlobal, setGlobal,\n} from '../../index';\n\nimport { ApiChat, 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 selectCurrentMediaSearch,\n selectCurrentMessageList,\n selectChat,\n selectThreadInfo,\n} from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n addChatMessagesById,\n addChats,\n addUsers,\n updateLocalMediaSearchResults,\n updateLocalTextSearchResults,\n} from '../../reducers';\nimport { SharedMediaType } from '../../../types';\n\naddActionHandler('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\naddActionHandler('searchMediaMessagesLocal', (global) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return;\n }\n\n const chat = selectChat(global, chatId);\n const currentSearch = selectCurrentMediaSearch(global);\n\n if (!chat || !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(chat, type, offsetId);\n});\n\naddActionHandler('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 chat: ApiChat,\n threadId: number,\n topMessageId?: number,\n query?: string,\n offsetId?: number,\n) {\n if (!query) {\n return;\n }\n\n const result = await callApi('searchMessagesLocal', {\n chat,\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 chats, users, messages, 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 !== currentSearch.query) {\n return;\n }\n\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = addChatMessagesById(global, chat.id, byId);\n global = updateLocalTextSearchResults(global, chat.id, threadId, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n}\n\nasync function searchSharedMedia(\n chat: ApiChat,\n type: SharedMediaType,\n offsetId?: number,\n isBudgetPreload = false,\n) {\n const result = await callApi('searchMessagesLocal', {\n chat,\n type,\n limit: SHARED_MEDIA_SLICE * 2,\n offsetId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n chats, users, messages, 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 = addChats(global, buildCollectionByKey(chats, 'id'));\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = addChatMessagesById(global, chat.id, byId);\n global = updateLocalMediaSearchResults(global, chat.id, type, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n\n if (!isBudgetPreload) {\n searchSharedMedia(chat, type, nextOffsetId, true);\n }\n}\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 getActions().focusMessage({\n chatId: chat.id,\n messageId,\n });\n}\n","import { addActionHandler, getGlobal, setGlobal } from '../../index';\n\nimport { ManagementProgress } from '../../../types';\nimport { callApi } from '../../../api/gramjs';\nimport { updateChat, updateManagement, updateManagementProgress } from '../../reducers';\nimport { selectChat, selectCurrentMessageList, selectUser } from '../../selectors';\nimport { isChatBasicGroup } from '../../helpers';\n\naddActionHandler('checkPublicLink', async (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return undefined;\n }\n\n // No need to check the username if already in progress\n if (global.management.progress === ManagementProgress.InProgress) {\n return undefined;\n }\n\n const { username } = payload!;\n\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 return global;\n});\n\naddActionHandler('updatePublicLink', async (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n let chat = chatId && selectChat(global, chatId);\n if (!chatId || !chat) {\n return undefined;\n }\n\n const { username } = payload!;\n\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 undefined;\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 return global;\n});\n\naddActionHandler('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\naddActionHandler('setEditingExportedInvite', (global, actions, payload) => {\n const { chatId, invite } = payload;\n\n setGlobal(updateManagement(global, chatId, { editingInvite: invite }));\n});\n\naddActionHandler('setOpenedInviteInfo', (global, actions, payload) => {\n const { chatId, invite } = payload;\n\n const update = invite ? { inviteInfo: { invite } } : { inviteInfo: undefined };\n\n setGlobal(updateManagement(global, chatId, update));\n});\n\naddActionHandler('loadExportedChatInvites', async (global, actions, payload) => {\n const {\n chatId, adminId, isRevoked, limit,\n } = payload!;\n const peer = selectChat(global, chatId);\n const admin = selectUser(global, adminId || global.currentUserId);\n if (!peer || !admin) return undefined;\n\n const result = await callApi('fetchExportedChatInvites', {\n peer, admin, isRevoked, limit,\n });\n if (!result) {\n return undefined;\n }\n\n const update = isRevoked ? { revokedInvites: result } : { invites: result };\n\n return updateManagement(getGlobal(), chatId, update);\n});\n\naddActionHandler('editExportedChatInvite', async (global, actions, payload) => {\n const {\n chatId, link, isRevoked, expireDate, usageLimit, isRequestNeeded, title,\n } = payload!;\n const peer = selectChat(global, chatId);\n if (!peer) return undefined;\n\n const result = await callApi('editExportedChatInvite', {\n peer,\n link,\n isRevoked,\n expireDate,\n usageLimit,\n isRequestNeeded,\n title,\n });\n if (!result) {\n return undefined;\n }\n\n const { oldInvite, newInvite } = result;\n\n global = getGlobal();\n const invites = (global.management.byChatId[chatId].invites || [])\n .filter((current) => current.link !== oldInvite.link);\n const revokedInvites = [...(global.management.byChatId[chatId].revokedInvites || [])];\n\n if (newInvite.isRevoked) {\n revokedInvites.unshift(newInvite);\n } else {\n invites.push(newInvite);\n }\n\n return updateManagement(global, chatId, {\n invites,\n revokedInvites,\n });\n});\n\naddActionHandler('exportChatInvite', async (global, actions, payload) => {\n const {\n chatId, expireDate, usageLimit, isRequestNeeded, title,\n } = payload!;\n const peer = selectChat(global, chatId);\n if (!peer) return undefined;\n\n const result = await callApi('exportChatInvite', {\n peer,\n expireDate,\n usageLimit,\n isRequestNeeded,\n title,\n });\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n const invites = global.management.byChatId[chatId].invites || [];\n return updateManagement(global, chatId, {\n invites: [...invites, result],\n });\n});\n\naddActionHandler('deleteExportedChatInvite', async (global, actions, payload) => {\n const {\n chatId, link,\n } = payload!;\n const peer = selectChat(global, chatId);\n if (!peer) return undefined;\n\n const result = await callApi('deleteExportedChatInvite', {\n peer,\n link,\n });\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n const managementState = global.management.byChatId[chatId];\n return updateManagement(global, chatId, {\n invites: managementState?.invites?.filter((invite) => invite.link !== link),\n revokedInvites: managementState?.revokedInvites?.filter((invite) => invite.link !== link),\n });\n});\n\naddActionHandler('deleteRevokedExportedChatInvites', async (global, actions, payload) => {\n const {\n chatId, adminId,\n } = payload!;\n const peer = selectChat(global, chatId);\n const admin = selectUser(global, adminId || global.currentUserId);\n if (!peer || !admin) return undefined;\n\n const result = await callApi('deleteRevokedExportedChatInvites', {\n peer,\n admin,\n });\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n return updateManagement(global, chatId, {\n revokedInvites: [],\n });\n});\n\naddActionHandler('loadChatInviteImporters', async (global, actions, payload) => {\n const {\n chatId, link, offsetDate, offsetUserId, limit,\n } = payload!;\n const peer = selectChat(global, chatId);\n const offsetUser = selectUser(global, offsetUserId);\n if (!peer || (offsetUserId && !offsetUser)) return undefined;\n\n const result = await callApi('fetchChatInviteImporters', {\n peer,\n link,\n offsetDate,\n offsetUser,\n limit,\n });\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n const currentInviteInfo = global.management.byChatId[chatId]?.inviteInfo;\n if (!currentInviteInfo?.invite || currentInviteInfo.invite.link !== link) {\n return undefined;\n }\n\n return updateManagement(global, chatId, {\n inviteInfo: {\n ...currentInviteInfo,\n importers: result,\n },\n });\n});\n\naddActionHandler('loadChatInviteRequesters', async (global, actions, payload) => {\n const {\n chatId, link, offsetDate, offsetUserId, limit,\n } = payload!;\n const peer = selectChat(global, chatId);\n const offsetUser = selectUser(global, offsetUserId);\n if (!peer || (offsetUserId && !offsetUser)) return undefined;\n\n const result = await callApi('fetchChatInviteImporters', {\n peer,\n link,\n offsetDate,\n offsetUser,\n limit,\n isRequested: true,\n });\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n const currentInviteInfo = global.management.byChatId[chatId]?.inviteInfo;\n if (!currentInviteInfo?.invite || currentInviteInfo.invite.link !== link) {\n return undefined;\n }\n\n return updateManagement(global, chatId, {\n inviteInfo: {\n ...currentInviteInfo,\n requesters: result,\n },\n });\n});\n\naddActionHandler('loadChatJoinRequests', async (global, actions, payload) => {\n const {\n chatId, offsetDate, offsetUserId, limit,\n } = payload!;\n const peer = selectChat(global, chatId);\n const offsetUser = selectUser(global, offsetUserId);\n if (!peer || (offsetUserId && !offsetUser)) return undefined;\n\n const result = await callApi('fetchChatInviteImporters', {\n peer,\n offsetDate,\n offsetUser,\n limit,\n isRequested: true,\n });\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n return updateChat(global, chatId, { joinRequests: result });\n});\n\naddActionHandler('hideChatJoinRequest', async (global, actions, payload) => {\n const {\n chatId, userId, isApproved,\n } = payload!;\n const peer = selectChat(global, chatId);\n const user = selectUser(global, userId);\n if (!peer || !user) return undefined;\n\n const result = await callApi('hideChatJoinRequest', {\n peer,\n user,\n isApproved,\n });\n if (!result) return undefined;\n\n global = getGlobal();\n const targetChat = selectChat(global, chatId);\n if (!targetChat) return undefined;\n\n return updateChat(global, chatId, {\n joinRequests: targetChat.joinRequests?.filter((importer) => importer.userId !== userId),\n });\n});\n\naddActionHandler('hideAllChatJoinRequests', async (global, actions, payload) => {\n const {\n chatId, isApproved, link,\n } = payload!;\n const peer = selectChat(global, chatId);\n if (!peer) return undefined;\n\n const result = await callApi('hideAllChatJoinRequests', {\n peer,\n isApproved,\n link,\n });\n if (!result) return undefined;\n\n global = getGlobal();\n const targetChat = selectChat(global, chatId);\n if (!targetChat) return undefined;\n\n return updateChat(global, chatId, {\n joinRequests: [],\n fullInfo: {\n ...targetChat.fullInfo,\n recentRequesterIds: [],\n requestsPending: 0,\n },\n });\n});\n\naddActionHandler('hideChatReportPanel', async (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) return undefined;\n\n const result = await callApi('hideChatReportPanel', chat);\n if (!result) return undefined;\n\n return updateChat(getGlobal(), chatId, {\n settings: undefined,\n });\n});\n","import {\n addActionHandler, getGlobal, setGlobal, getActions,\n} from '../../index';\n\nimport {\n ApiChat, ApiMessage, MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { Thread } from '../../types';\n\nimport {\n DEBUG, MESSAGE_LIST_SLICE, SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n updateUsers,\n updateChats,\n updateThreadInfos,\n updateListedIds,\n safeReplaceViewportIds,\n addChatMessagesById,\n updateThread,\n} from '../../reducers';\nimport {\n selectCurrentMessageList,\n selectDraft,\n selectChatMessage,\n selectThreadInfo,\n selectEditingId,\n selectEditingDraft,\n} from '../../selectors';\nimport { init as initFolderManager } from '../../../util/folderManager';\n\nconst RELEASE_STATUS_TIMEOUT = 15000; // 10 sec;\n\nlet releaseStatusTimeout: number | undefined;\n\naddActionHandler('sync', () => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START SYNC');\n }\n\n if (releaseStatusTimeout) {\n clearTimeout(releaseStatusTimeout);\n }\n\n setGlobal({ ...getGlobal(), isSyncing: true });\n\n // Workaround for `isSyncing = true` sometimes getting stuck for some reason\n releaseStatusTimeout = window.setTimeout(() => {\n setGlobal({ ...getGlobal(), isSyncing: false });\n releaseStatusTimeout = undefined;\n }, RELEASE_STATUS_TIMEOUT);\n\n const { loadAllChats, preloadTopChatMessages } = getActions();\n\n loadAllChats({\n listType: 'active',\n shouldReplace: true,\n onReplace: async () => {\n await loadAndReplaceMessages();\n\n setGlobal({\n ...getGlobal(),\n lastSyncTime: Date.now(),\n isSyncing: false,\n });\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH SYNC');\n }\n\n initFolderManager();\n loadAllChats({ listType: 'archived', shouldReplace: true });\n void callApi('fetchCurrentUser');\n preloadTopChatMessages();\n },\n });\n});\n\nasync function loadAndReplaceMessages() {\n let areMessagesLoaded = false;\n\n let global = getGlobal();\n\n // Memoize drafts\n const draftChatIds = Object.keys(global.messages.byChatId);\n const draftsByChatId = draftChatIds.reduce>>((acc, chatId) => {\n acc[chatId] = {};\n acc[chatId].draft = selectDraft(global, chatId, MAIN_THREAD_ID);\n acc[chatId].editingId = selectEditingId(global, chatId, MAIN_THREAD_ID);\n acc[chatId].editingDraft = selectEditingDraft(global, chatId, MAIN_THREAD_ID);\n\n return acc;\n }, {});\n\n const { chatId: currentChatId, threadId: currentThreadId } = selectCurrentMessageList(global) || {};\n const currentChat = currentChatId ? global.chats.byId[currentChatId] : undefined;\n if (currentChatId && currentChat) {\n const result = await loadTopMessages(currentChat);\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 = updateUsers(global, buildCollectionByKey(result.users, 'id'));\n global = updateThreadInfos(global, currentChatId, result.threadInfos);\n\n areMessagesLoaded = true;\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 = updateThread(global, chatId, MAIN_THREAD_ID, draftsByChatId[chatId]);\n });\n\n setGlobal(global);\n\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n if (audioChatId && audioMessageId && !selectChatMessage(global, audioChatId, audioMessageId)) {\n getActions().closeAudioPlayer();\n }\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 addActionHandler, getActions, getGlobal, setGlobal,\n} from '../../index';\n\nimport { ApiUser } from '../../../api/types';\nimport { ManagementProgress } from '../../../types';\n\nimport { debounce, throttle } from '../../../util/schedulers';\nimport { buildCollectionByKey, unique } from '../../../util/iteratees';\nimport { isUserBot, isUserId } from '../../helpers';\nimport { callApi } from '../../../api/gramjs';\nimport { selectChat, selectCurrentMessageList, selectUser } from '../../selectors';\nimport {\n addChats, addUsers, closeNewContactDialog, replaceUserStatuses, updateChat, updateManagementProgress, updateUser,\n updateUsers, updateUserSearch, updateUserSearchFetchingStatus,\n} from '../../reducers';\nimport { getServerTime } from '../../../util/serverTime';\nimport * as langProvider from '../../../util/langProvider';\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\naddActionHandler('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\naddActionHandler('loadUser', async (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return undefined;\n }\n\n const result = await callApi('fetchUsers', { users: [user] });\n if (!result) {\n return undefined;\n }\n\n const { users, userStatusesById } = result;\n\n global = getGlobal();\n\n global = updateUsers(global, buildCollectionByKey(users, 'id'));\n global = replaceUserStatuses(global, {\n ...global.users.statusesById,\n ...userStatusesById,\n });\n\n return global;\n});\n\naddActionHandler('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\naddActionHandler('loadContactList', () => {\n void loadContactList();\n});\n\naddActionHandler('loadCurrentUser', () => {\n void callApi('fetchCurrentUser');\n});\n\naddActionHandler('loadCommonChats', async (global) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const user = chatId ? selectUser(global, chatId) : undefined;\n if (!user || isUserBot(user) || user.commonChats?.isFullyLoaded) {\n return undefined;\n }\n\n const maxId = user.commonChats?.maxId;\n const result = await callApi('fetchCommonChats', user.id, user.accessHash!, maxId);\n if (!result) {\n return undefined;\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\n return global;\n});\n\naddActionHandler('updateContact', (global, actions, payload) => {\n const {\n userId, isMuted = false, firstName, lastName, shouldSharePhoneNumber,\n } = payload;\n\n void updateContact(userId, isMuted, firstName, lastName, shouldSharePhoneNumber);\n});\n\naddActionHandler('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 shouldSharePhoneNumber?: boolean,\n) {\n let global = getGlobal();\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n getActions().updateChatMutedState({ chatId: userId, isMuted });\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.InProgress));\n\n let result;\n if (!user.isContact && user.phoneNumber) {\n result = await callApi('importContact', { phone: user.phoneNumber, firstName, lastName });\n } else {\n const { id, accessHash } = user;\n result = await callApi('updateContact', {\n id,\n accessHash,\n phoneNumber: '',\n firstName,\n lastName,\n shouldSharePhoneNumber,\n });\n }\n\n global = getGlobal();\n if (result) {\n setGlobal(updateUser(\n global,\n user.id,\n {\n firstName,\n lastName,\n },\n ));\n }\n\n global = updateManagementProgress(global, ManagementProgress.Complete);\n global = closeNewContactDialog(global);\n setGlobal(global);\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\naddActionHandler('loadProfilePhotos', async (global, actions, payload) => {\n const { profileId } = payload!;\n const isPrivate = isUserId(profileId);\n\n const user = isPrivate ? selectUser(global, profileId) : undefined;\n const chat = !isPrivate ? selectChat(global, profileId) : undefined;\n if (!user && !chat) {\n return undefined;\n }\n\n const result = await callApi('fetchProfilePhotos', user, chat);\n if (!result || !result.photos) {\n return undefined;\n }\n\n global = getGlobal();\n\n if (isPrivate) {\n global = updateUser(global, profileId, { photos: result.photos });\n } else {\n global = addUsers(global, buildCollectionByKey(result.users!, 'id'));\n global = updateChat(global, profileId, { photos: result.photos });\n }\n\n return global;\n});\n\naddActionHandler('setUserSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (!query) return;\n\n void runThrottledForSearch(() => {\n searchUsers(query);\n });\n});\n\naddActionHandler('importContact', async (global, actions, payload) => {\n const { phoneNumber: phone, firstName, lastName } = payload!;\n\n const result = await callApi('importContact', { phone, firstName, lastName });\n\n if (result) {\n actions.openChat({ id: result });\n\n return closeNewContactDialog(getGlobal());\n }\n\n actions.showNotification({\n message: langProvider.getTranslation('Contacts.PhoneNumber.NotRegistred'),\n });\n\n return undefined;\n});\n\naddActionHandler('reportSpam', (global, actions, payload) => {\n const { chatId } = payload!;\n const userOrChat = isUserId(chatId) ? selectUser(global, chatId) : selectChat(global, chatId);\n if (!userOrChat) {\n return;\n }\n\n void callApi('reportSpam', userOrChat);\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 '../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 addActionHandler, getActions, getGlobal, setGlobal,\n} from '../../index';\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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('restartBot', async (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 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\naddActionHandler('loadTopInlineBots', async (global) => {\n const { lastRequestedAt } = global.topInlineBots;\n if (lastRequestedAt && getServerTime(global.serverTimeOffset) - lastRequestedAt < TOP_PEERS_REQUEST_COOLDOWN) {\n return undefined;\n }\n\n const result = await callApi('fetchTopInlineBots');\n if (!result) {\n return undefined;\n }\n\n const { ids, users } = result;\n\n global = getGlobal();\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = {\n ...global,\n topInlineBots: {\n ...global.topInlineBots,\n userIds: ids,\n lastRequestedAt: getServerTime(global.serverTimeOffset),\n },\n };\n return global;\n});\n\naddActionHandler('queryInlineBot', async (global, actions, payload) => {\n const {\n chatId, username, query, offset,\n } = payload;\n\n let inlineBotData = global.inlineBots.byUsername[username];\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\naddActionHandler('sendInlineBotResult', (global, actions, payload) => {\n const {\n id, queryId, isSilent, scheduledAt,\n } = payload;\n const currentMessageList = selectCurrentMessageList(global);\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 isSilent,\n scheduleDate: scheduledAt,\n });\n});\n\naddActionHandler('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\naddActionHandler('startBot', async (global, actions, payload) => {\n const { botId, param } = payload;\n\n const bot = selectUser(global, botId);\n if (!bot) {\n return;\n }\n\n await callApi('startBot', {\n bot,\n startParam: param,\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 } = getActions();\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 { addActionHandler, getGlobal, setGlobal } from '../../index';\n\nimport { callApi } from '../../../api/gramjs';\nimport { replaceSettings, updateTwoFaSettings } from '../../reducers';\n\naddActionHandler('loadPasswordInfo', async (global) => {\n const result = await callApi('getPasswordInfo');\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n global = replaceSettings(global, { hasPassword: result.hasPassword });\n global = updateTwoFaSettings(global, { hint: result.hint });\n return global;\n});\n\naddActionHandler('checkPassword', async (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n const isSuccess = await callApi('checkPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n});\n\naddActionHandler('clearPassword', async (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n const isSuccess = await callApi('clearPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n});\n\naddActionHandler('updatePassword', async (global, actions, payload) => {\n const {\n currentPassword, password, hint, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\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\naddActionHandler('updateRecoveryEmail', async (global, actions, payload) => {\n const {\n currentPassword, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\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\naddActionHandler('provideTwoFaEmailCode', (global, actions, payload) => {\n const { code } = payload;\n\n void callApi('provideRecoveryEmailCode', code);\n});\n\naddActionHandler('clearTwoFaError', (global) => {\n return updateTwoFaSettings(global, { error: undefined });\n});\n","import { addActionHandler, getGlobal, setGlobal } from '../../index';\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 selectProviderPublicToken,\n selectSmartGlocalCredentials,\n} from '../../selectors';\nimport { callApi } from '../../../api/gramjs';\nimport { getStripeError } from '../../helpers';\nimport { buildQueryString } from '../../../util/requestQuery';\nimport { DEBUG_PAYMENT_SMART_GLOCAL } from '../../../config';\n\nimport {\n updateShippingOptions,\n setPaymentStep,\n setRequestInfoId,\n setPaymentForm,\n setStripeCardInfo,\n setInvoiceMessageInfo,\n setReceipt,\n clearPayment,\n closeInvoice,\n setSmartGlocalCardInfo,\n} from '../../reducers';\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('clearPaymentError', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n error: undefined,\n },\n });\n});\n\naddActionHandler('clearReceipt', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n });\n});\n\naddActionHandler('sendCredentialsInfo', (global, actions, payload) => {\n const { nativeProvider } = global.payment;\n const { credentials } = payload;\n const { data } = credentials;\n\n if (nativeProvider === 'stripe') {\n const publishableKey = selectProviderPublishableKey(global);\n if (!publishableKey) {\n return;\n }\n void sendStripeCredentials(data, publishableKey);\n } else if (nativeProvider === 'smartglocal') {\n const publicToken = selectProviderPublicToken(global);\n if (!publicToken) {\n return;\n }\n void sendSmartGlocalCredentials(data, publicToken);\n }\n});\n\naddActionHandler('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 { nativeProvider } = global.payment;\n const publishableKey = nativeProvider === 'stripe'\n ? selectProviderPublishableKey(global) : selectProviderPublicToken(global);\n if (!chat || !messageId || !publishableKey || !formId || !nativeProvider) {\n return;\n }\n\n void sendPaymentForm(chat, messageId, nativeProvider, formId, {\n save: saveCredentials,\n data: nativeProvider === 'stripe' ? selectStripeCredentials(global) : selectSmartGlocalCredentials(global),\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 sendSmartGlocalCredentials(\n data: {\n cardNumber: string;\n cardholder?: string;\n expiryMonth: string;\n expiryYear: string;\n cvv: string;\n },\n publicToken: string,\n) {\n const params = {\n card: {\n number: data.cardNumber.replace(/[^\\d]+/g, ''),\n expiration_month: data.expiryMonth,\n expiration_year: data.expiryYear,\n security_code: data.cvv.replace(/[^\\d]+/g, ''),\n },\n };\n const url = DEBUG_PAYMENT_SMART_GLOCAL\n ? 'https://tgb-playground.smart-glocal.com/cds/v1/tokenize/card'\n : 'https://tgb.smart-glocal.com/cds/v1/tokenize/card';\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'X-PUBLIC-TOKEN': publicToken,\n },\n body: JSON.stringify(params),\n });\n const result = await response.json();\n\n if (result.status !== 'ok') {\n // TODO после получения документации сделать аналог getStripeError(result.error);\n const error = { description: 'payment 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\n let global = setSmartGlocalCardInfo(getGlobal(), {\n type: 'card',\n token: result.data.token,\n });\n global = setPaymentStep(global, PaymentStep.Checkout);\n setGlobal(global);\n}\n\nasync function sendPaymentForm(\n chat: ApiChat,\n messageId: number,\n nativeProvider: string,\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\n if (result === true) {\n const global = clearPayment(getGlobal());\n setGlobal(closeInvoice(global));\n }\n}\n\naddActionHandler('setPaymentStep', (global, actions, payload = {}) => {\n return setPaymentStep(global, payload.step || PaymentStep.ShippingInfo);\n});\n\naddActionHandler('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 {\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;\nexport const SIDE_COLUMN_MAX_WIDTH = 26.5 * REM;\nexport const 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 { updateChatMessage } from './messages';\nimport { GlobalState } from '../types';\nimport { selectChatMessage } from '../selectors';\nimport { MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN, MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN } from '../../config';\nimport {\n MIN_LEFT_COLUMN_WIDTH,\n SIDE_COLUMN_MAX_WIDTH,\n} from '../../components/middle/helpers/calculateMiddleFooterTransforms';\nimport { IS_SINGLE_COLUMN_LAYOUT } from '../../util/environment';\nimport windowSize from '../../util/windowSize';\n\nfunction getLeftColumnWidth(windowWidth: number) {\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN) {\n return Math.min(\n Math.max(windowWidth * 0.25, MIN_LEFT_COLUMN_WIDTH),\n windowWidth * 0.33,\n );\n }\n\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN) {\n return Math.min(\n Math.max(windowWidth * 0.33, MIN_LEFT_COLUMN_WIDTH),\n windowWidth * 0.4,\n );\n }\n\n return SIDE_COLUMN_MAX_WIDTH;\n}\n\nexport function subtractXForEmojiInteraction(global: GlobalState, x: number) {\n return x - ((global.isLeftColumnShown && !IS_SINGLE_COLUMN_LAYOUT)\n ? global.leftColumnWidth || getLeftColumnWidth(windowSize.get().width)\n : 0);\n}\n\nexport function addMessageReaction(global: GlobalState, chatId: string, messageId: number, reaction: string) {\n const { reactions } = selectChatMessage(global, chatId, messageId) || {};\n\n if (!reactions) {\n return global;\n }\n\n // Update UI without waiting for server response\n let results = reactions.results.map((l) => (l.reaction === reaction\n ? {\n ...l,\n count: l.isChosen ? l.count : l.count + 1,\n isChosen: true,\n } : (l.isChosen ? {\n ...l,\n isChosen: false,\n count: l.count - 1,\n } : l)))\n .filter((l) => l.count > 0);\n\n let { recentReactions } = reactions;\n\n if (reaction && !results.some((l) => l.reaction === reaction)) {\n const { currentUserId } = global;\n\n results = [...results, {\n reaction,\n isChosen: true,\n count: 1,\n }];\n\n if (reactions.canSeeList) {\n recentReactions = [...(recentReactions || []), {\n userId: currentUserId!,\n reaction,\n }];\n }\n }\n\n return updateChatMessage(global, chatId, messageId, {\n reactions: {\n ...reactions,\n results,\n recentReactions,\n },\n });\n}\n","import { addActionHandler, getGlobal } from '../../index';\nimport { callApi } from '../../../api/gramjs';\nimport * as mediaLoader from '../../../util/mediaLoader';\nimport { ApiAppConfig, ApiMediaFormat } from '../../../api/types';\nimport {\n selectChat,\n selectChatMessage,\n selectDefaultReaction,\n selectLocalAnimatedEmojiEffectByName,\n selectMessageIdsByGroupId,\n} from '../../selectors';\nimport { addMessageReaction, subtractXForEmojiInteraction } from '../../reducers/reactions';\nimport { addUsers, updateChatMessage } from '../../reducers';\nimport { buildCollectionByKey, omit } from '../../../util/iteratees';\nimport { ANIMATION_LEVEL_MAX } from '../../../config';\nimport { isMessageLocal } from '../../helpers';\n\nconst INTERACTION_RANDOM_OFFSET = 40;\n\nlet interactionLocalId = 0;\n\naddActionHandler('loadAvailableReactions', async () => {\n const result = await callApi('getAvailableReactions');\n if (!result) {\n return undefined;\n }\n\n // Preload animations\n result.forEach((availableReaction) => {\n if (availableReaction.aroundAnimation) {\n mediaLoader.fetch(`sticker${availableReaction.aroundAnimation.id}`, ApiMediaFormat.Lottie);\n }\n if (availableReaction.centerIcon) {\n mediaLoader.fetch(`sticker${availableReaction.centerIcon.id}`, ApiMediaFormat.Lottie);\n }\n });\n\n return {\n ...getGlobal(),\n availableReactions: result,\n };\n});\n\naddActionHandler('interactWithAnimatedEmoji', (global, actions, payload) => {\n const {\n emoji, x, y, localEffect, startSize, isReversed,\n } = payload!;\n\n const activeEmojiInteraction = {\n id: interactionLocalId++,\n animatedEffect: emoji || localEffect,\n x: subtractXForEmojiInteraction(global, x) + Math.random()\n * INTERACTION_RANDOM_OFFSET - INTERACTION_RANDOM_OFFSET / 2,\n y: y + Math.random() * INTERACTION_RANDOM_OFFSET - INTERACTION_RANDOM_OFFSET / 2,\n startSize,\n isReversed,\n };\n\n return {\n ...global,\n activeEmojiInteractions: [...(global.activeEmojiInteractions || []), activeEmojiInteraction],\n };\n});\n\naddActionHandler('sendEmojiInteraction', (global, actions, payload) => {\n const {\n messageId, chatId, emoji, interactions, localEffect,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n\n if (!chat || (!emoji && !localEffect) || chatId === global.currentUserId) {\n return;\n }\n\n void callApi('sendEmojiInteraction', {\n chat,\n messageId,\n emoticon: emoji || selectLocalAnimatedEmojiEffectByName(localEffect),\n timestamps: interactions,\n });\n});\n\naddActionHandler('sendDefaultReaction', (global, actions, payload) => {\n const {\n chatId, messageId, x, y,\n } = payload;\n const reaction = selectDefaultReaction(global, chatId);\n const message = selectChatMessage(global, chatId, messageId);\n\n if (!reaction || !message || isMessageLocal(message)) return;\n\n actions.sendReaction({\n chatId,\n messageId,\n reaction,\n x,\n y,\n });\n});\n\naddActionHandler('sendReaction', (global, actions, payload) => {\n const {\n chatId,\n }: { chatId: string } = payload;\n let { messageId } = payload;\n\n let { reaction } = payload;\n\n const chat = selectChat(global, chatId);\n let message = selectChatMessage(global, chatId, messageId);\n\n if (!chat || !message) {\n return undefined;\n }\n\n const isInDocumentGroup = Boolean(message.groupedId) && !message.isInAlbum;\n const documentGroupFirstMessageId = isInDocumentGroup\n ? selectMessageIdsByGroupId(global, chatId, message.groupedId!)![0]\n : undefined;\n message = isInDocumentGroup\n ? selectChatMessage(global, chatId, documentGroupFirstMessageId!) || message\n : message;\n messageId = message?.id || messageId;\n\n if (message.reactions?.results?.some((l) => l.reaction === reaction && l.isChosen)) {\n reaction = undefined;\n }\n\n void callApi('sendReaction', { chat, messageId, reaction });\n\n const { animationLevel } = global.settings.byKey;\n\n if (animationLevel === ANIMATION_LEVEL_MAX) {\n global = {\n ...global,\n activeReactions: {\n ...(reaction ? global.activeReactions : omit(global.activeReactions, [messageId])),\n ...(reaction && {\n [messageId]: {\n reaction,\n messageId,\n },\n }),\n },\n };\n }\n\n return addMessageReaction(global, chatId, messageId, reaction);\n});\n\naddActionHandler('openChat', (global) => {\n return {\n ...global,\n activeReactions: {},\n };\n});\n\naddActionHandler('startActiveReaction', (global, actions, payload) => {\n const { messageId, reaction } = payload;\n const { animationLevel } = global.settings.byKey;\n\n if (animationLevel !== ANIMATION_LEVEL_MAX) return global;\n\n if (global.activeReactions[messageId]?.reaction === reaction) {\n return global;\n }\n\n return {\n ...global,\n activeReactions: {\n ...(reaction ? global.activeReactions : omit(global.activeReactions, [messageId])),\n ...(reaction && {\n [messageId]: {\n reaction,\n messageId,\n },\n }),\n },\n };\n});\n\naddActionHandler('stopActiveReaction', (global, actions, payload) => {\n const { messageId, reaction } = payload;\n\n if (global.activeReactions[messageId]?.reaction !== reaction) {\n return global;\n }\n\n return {\n ...global,\n activeReactions: omit(global.activeReactions, [messageId]),\n };\n});\n\naddActionHandler('setDefaultReaction', async (global, actions, payload) => {\n const { reaction } = payload;\n\n const result = await callApi('setDefaultReaction', { reaction });\n if (!result) {\n return undefined;\n }\n\n return {\n ...getGlobal(),\n appConfig: {\n ...global.appConfig,\n defaultReaction: reaction,\n } as ApiAppConfig,\n };\n});\n\naddActionHandler('stopActiveEmojiInteraction', (global, actions, payload) => {\n const { id } = payload;\n\n return {\n ...global,\n activeEmojiInteractions: global.activeEmojiInteractions?.filter((l) => l.id !== id),\n };\n});\n\naddActionHandler('loadReactors', async (global, actions, payload) => {\n const { chatId, messageId, reaction } = payload;\n const chat = selectChat(global, chatId);\n const message = selectChatMessage(global, chatId, messageId);\n if (!chat || !message) {\n return undefined;\n }\n\n const offset = message.reactors?.nextOffset;\n const result = await callApi('fetchMessageReactionsList', {\n reaction,\n chat,\n messageId,\n offset,\n });\n\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n\n if (result.users?.length) {\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n }\n\n const { nextOffset, count, reactions } = result;\n\n return updateChatMessage(global, chatId, messageId, {\n reactors: {\n nextOffset,\n count,\n reactions: [\n ...(message.reactors?.reactions || []),\n ...reactions,\n ],\n },\n });\n});\n\naddActionHandler('loadMessageReactions', (global, actions, payload) => {\n const { ids, chatId } = payload;\n\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n callApi('fetchMessageReactions', { ids, chat });\n});\n\naddActionHandler('sendWatchingEmojiInteraction', (global, actions, payload) => {\n const {\n chatId, emoticon, x, y, startSize, isReversed, id,\n } = payload;\n\n const chat = selectChat(global, chatId);\n\n if (!chat || !global.activeEmojiInteractions?.some((l) => l.id === id) || chatId === global.currentUserId) {\n return undefined;\n }\n\n callApi('sendWatchingEmojiInteraction', { chat, emoticon });\n\n return {\n ...global,\n activeEmojiInteractions: global.activeEmojiInteractions.map((activeEmojiInteraction) => {\n if (activeEmojiInteraction.id === id) {\n return {\n ...activeEmojiInteraction,\n x: subtractXForEmojiInteraction(global, x),\n y,\n startSize,\n isReversed,\n };\n }\n return activeEmojiInteraction;\n }),\n };\n});\n","import { addActionHandler, getGlobal } from '../../index';\n\nimport { ApiChannelStatistics } from '../../../api/types';\nimport { callApi } from '../../../api/gramjs';\nimport { updateStatistics, updateStatisticsGraph } from '../../reducers';\nimport { selectChatMessages, selectChat } from '../../selectors';\n\naddActionHandler('loadStatistics', async (global, actions, payload) => {\n const { chatId, isGroup } = payload;\n const chat = selectChat(global, chatId);\n if (!chat?.fullInfo) {\n return undefined;\n }\n\n const result = await callApi(isGroup ? 'fetchGroupStatistics' : 'fetchChannelStatistics', { chat });\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n\n if ((result as ApiChannelStatistics).recentTopMessages?.length) {\n const messages = selectChatMessages(global, chatId);\n\n (result as ApiChannelStatistics).recentTopMessages = (result as ApiChannelStatistics).recentTopMessages\n .map((message) => ({ ...message, ...messages[message.msgId] }));\n }\n\n global = updateStatistics(global, chatId, result);\n\n return global;\n});\n\naddActionHandler('loadStatisticsAsyncGraph', async (global, actions, payload) => {\n const {\n chatId, token, name, isPercentage,\n } = payload;\n const chat = selectChat(global, chatId);\n if (!chat?.fullInfo) {\n return undefined;\n }\n\n const dcId = chat.fullInfo!.statisticsDcId;\n const result = await callApi('fetchStatisticsAsyncGraph', { token, dcId, isPercentage });\n\n if (!result) {\n return undefined;\n }\n\n return updateStatisticsGraph(getGlobal(), chatId, name, result);\n});\n","export function areDeepEqual(value1: T, value2: T): boolean {\n const type1 = typeof value1;\n const type2 = typeof value2;\n if (type1 !== type2) {\n return false;\n }\n\n if (type1 !== 'object') {\n return value1 === value2;\n }\n\n const isArray1 = Array.isArray(value1);\n const isArray2 = Array.isArray(value2);\n\n if (isArray1 !== isArray2) {\n return false;\n }\n\n if (isArray1) {\n const array1 = value1 as any[];\n const array2 = value2 as any[];\n\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((member1, i) => areDeepEqual(member1, array2[i]));\n }\n\n const object1 = value1 as AnyLiteral;\n const object2 = value2 as AnyLiteral;\n const keys1 = Object.keys(object1);\n\n return keys1.every((key1) => areDeepEqual(object1[key1], object2[key1]));\n}\n","import { addActionHandler, getGlobal, setGlobal } from '../../index';\n\nimport { MAIN_THREAD_ID } from '../../../api/types';\n\nimport { ARCHIVED_FOLDER_ID, MAX_ACTIVE_PINNED_CHATS } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { closeMessageNotifications, notifyAboutMessage } from '../../../util/notifications';\nimport { getMessageRecentReaction } from '../../helpers';\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} from '../../selectors';\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\naddActionHandler('apiUpdate', (global, actions, update) => {\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 setGlobal(updateChat(global, update.id, update.chat, update.newProfilePhoto));\n\n if (update.chat.id) {\n closeMessageNotifications({\n chatId: update.chat.id,\n lastReadInboxMessageId: update.chat.lastReadInboxMessageId,\n });\n }\n\n return undefined;\n }\n\n case 'updateChatJoin': {\n const listType = selectChatListType(global, update.id);\n if (!listType) {\n return undefined;\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\n return undefined;\n }\n\n case 'updateChatLeave': {\n return leaveChat(global, update.id);\n }\n\n case 'updateChatInbox': {\n return updateChat(global, update.id, update.chat);\n }\n\n case 'updateChatTypingStatus': {\n const { id, typingStatus } = update;\n setGlobal(updateChat(global, id, { typingStatus }));\n\n setTimeout(() => {\n global = getGlobal();\n const chat = selectChat(global, id);\n if (chat && typingStatus && chat.typingStatus && chat.typingStatus.timestamp === typingStatus.timestamp) {\n setGlobal(updateChat(global, id, { typingStatus: undefined }));\n }\n }, TYPING_STATUS_CLEAR_DELAY);\n\n return undefined;\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 undefined;\n }\n\n const chat = selectChat(global, update.chatId);\n if (!chat) {\n return undefined;\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 notifyAboutMessage({\n chat,\n message,\n });\n\n return undefined;\n }\n\n case 'updateMessage': {\n const { message } = update;\n const chat = selectChat(global, update.chatId);\n if (!chat) {\n return undefined;\n }\n\n if (getMessageRecentReaction(message)) {\n notifyAboutMessage({\n chat,\n message,\n });\n }\n\n return undefined;\n }\n\n case 'updateCommonBoxMessages':\n case 'updateChannelMessages': {\n const { ids, messageUpdate } = update;\n if (messageUpdate.hasUnreadMention !== false) {\n return undefined;\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 return global;\n }\n\n case 'updateChatFullInfo': {\n const { fullInfo } = update;\n const targetChat = global.chats.byId[update.id];\n if (!targetChat) {\n return undefined;\n }\n\n return updateChat(global, update.id, {\n fullInfo: {\n ...targetChat.fullInfo,\n ...fullInfo,\n },\n });\n }\n\n case 'updatePinnedChatIds': {\n const { ids, folderId } = update;\n const listType = folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n\n return {\n ...global,\n chats: {\n ...global.chats,\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [listType]: ids.length ? ids : undefined,\n },\n },\n };\n }\n\n case 'updateChatPinned': {\n const { id, isPinned } = update;\n const listType = selectChatListType(global, id);\n if (!listType) {\n return undefined;\n }\n\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 return {\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 case 'updateChatListType': {\n const { id, folderId } = update;\n\n return updateChatListType(global, id, folderId);\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 return {\n ...global,\n chatFolders: {\n ...global.chatFolders,\n byId: newChatFoldersById,\n orderedIds: newOrderedIds,\n },\n };\n }\n\n case 'updateChatFoldersOrder': {\n const { orderedIds } = update;\n\n return {\n ...global,\n chatFolders: {\n ...global.chatFolders,\n orderedIds,\n },\n };\n }\n\n case 'updateRecommendedChatFolders': {\n const { folders } = update;\n\n return {\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: folders,\n },\n };\n }\n\n case 'updateChatMembers': {\n const targetChat = global.chats.byId[update.id];\n const { replacedMembers, addedMember, deletedMemberId } = update;\n if (!targetChat) {\n return undefined;\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 return updateChat(global, update.id, {\n membersCount: members.length,\n fullInfo: {\n ...targetChat.fullInfo,\n members,\n adminMembers,\n },\n });\n }\n\n return undefined;\n }\n\n case 'deleteProfilePhotos': {\n const { chatId, ids } = update;\n const chat = global.chats.byId[chatId];\n\n if (chat?.photos) {\n return updateChat(global, chatId, {\n photos: chat.photos.filter((photo) => !ids.includes(photo.id)),\n });\n }\n\n return undefined;\n }\n\n case 'draftMessage': {\n const {\n chatId, formattedText, date, replyingToId,\n } = update;\n const chat = global.chats.byId[chatId];\n if (!chat) {\n return undefined;\n }\n\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 return global;\n }\n\n case 'showInvite': {\n const { data } = update;\n\n actions.showDialog({ data });\n\n return undefined;\n }\n\n case 'updatePendingJoinRequests': {\n const { chatId, requestsPending, recentRequesterIds } = update;\n const chat = global.chats.byId[chatId];\n if (!chat) {\n return undefined;\n }\n\n global = updateChat(global, chatId, {\n fullInfo: {\n ...chat.fullInfo,\n requestsPending,\n recentRequesterIds,\n },\n });\n setGlobal(global);\n\n actions.loadChatJoinRequests({ chatId });\n }\n }\n\n return undefined;\n});\n","import { addActionHandler, getGlobal, setGlobal } from '../../index';\n\nimport {\n ApiMessage, ApiPollResult, ApiThreadInfo, MAIN_THREAD_ID,\n} from '../../../api/types';\n\nimport { unique } from '../../../util/iteratees';\nimport { areDeepEqual } from '../../../util/areDeepEqual';\nimport { notifyAboutMessage } from '../../../util/notifications';\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 { ActiveEmojiInteraction, GlobalActions, GlobalState } from '../../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 selectIsMessageInCurrentMessageList,\n selectScheduledIds,\n selectCurrentMessageList,\n selectViewportIds,\n selectFirstUnreadId,\n selectChat,\n selectIsChatWithBot,\n selectIsServiceChatReady,\n selectLocalAnimatedEmojiEffect,\n selectLocalAnimatedEmoji,\n} from '../../selectors';\nimport {\n getMessageContent, isUserId, isMessageLocal, getMessageText, checkIfReactionAdded,\n} from '../../helpers';\n\nconst ANIMATION_DELAY = 350;\n\naddActionHandler('apiUpdate', (global, actions, update) => {\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 (selectIsMessageInCurrentMessageList(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 'updateStartEmojiInteraction': {\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n if (currentChatId !== update.id) return;\n const message = selectChatMessage(global, currentChatId, update.messageId);\n\n if (!message) return;\n\n // Workaround for a weird behavior when interaction is received after watching reaction\n if (getMessageText(message) !== update.emoji) return;\n\n const localEmoji = selectLocalAnimatedEmoji(global, update.emoji);\n\n global = {\n ...global,\n activeEmojiInteractions: [...(global.activeEmojiInteractions || []), {\n id: global.activeEmojiInteractions?.length || 0,\n animatedEffect: localEmoji ? selectLocalAnimatedEmojiEffect(localEmoji) : update.emoji,\n messageId: update.messageId,\n } as ActiveEmojiInteraction],\n };\n\n setGlobal(global);\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 && selectIsMessageInCurrentMessageList(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 case 'updateMessageReactions': {\n const { chatId, id, reactions } = update;\n const message = selectChatMessage(global, chatId, id);\n const chat = selectChat(global, update.chatId);\n const currentReactions = message?.reactions;\n\n // `updateMessageReactions` happens with an interval, so we try to avoid redundant global state updates\n if (currentReactions && areDeepEqual(reactions, currentReactions)) {\n return;\n }\n\n // Only notify about added reactions, not removed ones\n const shouldNotify = checkIfReactionAdded(currentReactions, reactions, global.currentUserId);\n\n global = updateChatMessage(global, chatId, id, { reactions: update.reactions });\n\n if (shouldNotify) {\n const newMessage = selectChatMessage(global, chatId, id);\n if (!chat || !newMessage) return;\n notifyAboutMessage({\n chat,\n message: newMessage,\n isReaction: true,\n });\n }\n\n setGlobal(global);\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 candidateGlobal = addViewportId(global, chatId, MAIN_THREAD_ID, id);\n const newViewportIds = selectViewportIds(candidateGlobal, chatId, MAIN_THREAD_ID);\n\n if (!firstUnreadId || newViewportIds!.includes(firstUnreadId)) {\n global = candidateGlobal;\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 { addActionHandler, getGlobal, setGlobal } from '../../index';\n\nimport { 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\naddActionHandler('apiUpdate', (global, actions, update) => {\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 { addActionHandler } from '../../index';\n\nimport { updateStickerSet } from '../../reducers';\n\naddActionHandler('apiUpdate', (global, actions, update) => {\n switch (update['@type']) {\n case 'updateStickerSet': {\n return updateStickerSet(global, update.id, update.stickerSet);\n }\n }\n\n return undefined;\n});\n","import { addActionHandler, getGlobal, setGlobal } from '../../index';\n\nimport { ApiPrivacyKey, PaymentStep } from '../../../types';\n\nimport {\n addBlockedContact, removeBlockedContact, setConfirmPaymentUrl, setPaymentStep,\n} from '../../reducers';\n\naddActionHandler('apiUpdate', (global, actions, update) => {\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 case 'updatePaymentVerificationNeeded':\n global = setConfirmPaymentUrl(getGlobal(), update.url);\n global = setPaymentStep(global, PaymentStep.ConfirmPayment);\n setGlobal(global);\n break;\n }\n\n return undefined;\n});\n","import { addActionHandler, setGlobal } from '../../index';\n\nimport { addNotifyException, updateChat, updateNotifySettings } from '../../reducers';\n\naddActionHandler('apiUpdate', (global, actions, update) => {\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 { addActionHandler } from '../../index';\n\naddActionHandler('apiUpdate', (global, actions, update) => {\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 { addActionHandler, getGlobal } from '../../index';\nimport { removeGroupCall, updateGroupCall, updateGroupCallParticipant } from '../../reducers/calls';\nimport { omit } from '../../../util/iteratees';\nimport { selectChat } from '../../selectors';\nimport { updateChat } from '../../reducers';\n\naddActionHandler('apiUpdate', (global, actions, update) => {\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(\n global, groupCallId, participant.id, participant, Boolean(nextOffset) || currentUserId === participant.id,\n );\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 { addActionHandler } from '../../index';\n\nimport { clearPayment } from '../../reducers';\n\naddActionHandler('apiUpdate', (global, actions, update) => {\n switch (update['@type']) {\n case 'updatePaymentStateCompleted': {\n return clearPayment(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 React, { FC, memo, useEffect } from '../../lib/teact/teact';\n\nimport { formatIntegerCompact } from '../../util/textFormat';\nimport { useFolderManagerForUnreadCounters } from '../../hooks/useFolderManager';\nimport { getAllNotificationsCount } from '../../util/folderManager';\nimport { updateAppBadge } from '../../util/appBadge';\n\ninterface OwnProps {\n isForAppBadge?: boolean;\n}\n\nconst UnreadCounter: FC = ({ isForAppBadge }) => {\n useFolderManagerForUnreadCounters();\n const unreadNotificationsCount = getAllNotificationsCount();\n\n useEffect(() => {\n if (isForAppBadge) {\n updateAppBadge(unreadNotificationsCount);\n }\n }, [isForAppBadge, unreadNotificationsCount]);\n\n if (isForAppBadge || !unreadNotificationsCount) {\n return undefined;\n }\n\n return (\n
{formatIntegerCompact(unreadNotificationsCount)}
\n );\n};\n\nexport default memo(UnreadCounter);\n","import { GlobalState } from '../global/types';\n\nimport useBrowserOnline from './useBrowserOnline';\nimport { LangFn } from './useLang';\n\nexport enum ConnectionStatus {\n waitingForNetwork,\n syncing,\n online,\n}\n\ntype ConnectionStatusPosition =\n 'overlay'\n | 'minimized'\n | 'middleHeader'\n | 'none';\n\nexport default function useConnectionStatus(\n lang: LangFn,\n connectionState: GlobalState['connectionState'],\n isSyncing: GlobalState['isSyncing'],\n hasMiddleHeader: boolean,\n isMinimized?: boolean,\n isDisabled?: boolean,\n) {\n let status: ConnectionStatus;\n const isBrowserOnline = useBrowserOnline();\n if (!isBrowserOnline || connectionState === 'connectionStateConnecting') {\n status = ConnectionStatus.waitingForNetwork;\n } else if (isSyncing) {\n status = ConnectionStatus.syncing;\n } else {\n status = ConnectionStatus.online;\n }\n\n let position: ConnectionStatusPosition;\n if (status === ConnectionStatus.online || isDisabled) {\n position = 'none';\n } else if (hasMiddleHeader) {\n position = 'middleHeader';\n } else if (isMinimized) {\n position = 'minimized';\n } else {\n position = 'overlay';\n }\n\n let text: string | undefined;\n if (status === ConnectionStatus.waitingForNetwork) {\n text = lang('WaitingForNetwork');\n } else if (status === ConnectionStatus.syncing) {\n text = lang('Updating');\n }\n\n if (position === 'middleHeader') {\n text = text!.toLowerCase().replace(/\\.+$/, '');\n }\n\n return {\n connectionStatus: status,\n connectionStatusPosition: position,\n connectionStatusText: text,\n };\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, { FC, memo } from '../../lib/teact/teact';\n\nimport useLang from '../../hooks/useLang';\nimport { ConnectionStatus } from '../../hooks/useConnectionStatus';\n\nimport Transition from '../ui/Transition';\nimport Spinner from '../ui/Spinner';\nimport Button from '../ui/Button';\n\nimport './ConnectionStatusOverlay.scss';\n\ntype OwnProps = {\n connectionStatus: ConnectionStatus;\n connectionStatusText: string;\n onClick?: NoneToVoidFunction;\n};\n\nconst ConnectionStatusOverlay: FC = ({\n connectionStatus,\n connectionStatusText,\n onClick,\n}) => {\n const lang = useLang();\n\n return (\n
\n \n
\n \n {connectionStatusText}\n \n
\n \n \n \n
\n );\n};\n\nexport default memo(ConnectionStatusOverlay);\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../../global';\n\nimport { ISettings, LeftColumnContent } from '../../../types';\nimport { ApiChat } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\n\nimport {\n ANIMATION_LEVEL_MAX, APP_NAME, APP_VERSION, DEBUG, 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 { clearWebsync } from '../../../util/websync';\nimport { selectCurrentMessageList, selectTheme } from '../../../global/selectors';\nimport { isChatArchived } from '../../../global/helpers';\nimport useLang from '../../../hooks/useLang';\nimport { disableHistoryBack } from '../../../hooks/useHistoryBack';\nimport useConnectionStatus from '../../../hooks/useConnectionStatus';\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';\nimport ShowTransition from '../../ui/ShowTransition';\nimport ConnectionStatusOverlay from '../ConnectionStatusOverlay';\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 {\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 isMessageListOpen: boolean;\n isConnectionStatusMinimized: ISettings['isConnectionStatusMinimized'];\n areChatsLoaded?: boolean;\n }\n & Pick;\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 connectionState,\n isSyncing,\n isMessageListOpen,\n isConnectionStatusMinimized,\n areChatsLoaded,\n}) => {\n const {\n openChat,\n openTipsChat,\n setGlobalSearchDate,\n setSettingOption,\n setGlobalSearchChatId,\n } = getActions();\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 { connectionStatus, connectionStatusText, connectionStatusPosition } = useConnectionStatus(\n lang, connectionState, isSyncing, isMessageListOpen, isConnectionStatusMinimized, !areChatsLoaded,\n );\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 toggleConnectionStatus = useCallback(() => {\n setSettingOption({ isConnectionStatusMinimized: !isConnectionStatusMinimized });\n }, [isConnectionStatusMinimized, setSettingOption]);\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 clearWebsync();\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
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n query: searchQuery, fetchingStatus, chatId, date,\n } = global.globalSearch;\n const { currentUserId, connectionState, isSyncing } = global;\n const { byId: chatsById } = global.chats;\n const { isConnectionStatusMinimized, 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 connectionState,\n isSyncing,\n isMessageListOpen: Boolean(selectCurrentMessageList(global)),\n isConnectionStatusMinimized,\n areChatsLoaded: Boolean(global.chats.listIds.active),\n };\n },\n)(LeftMainHeader));\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef,\n} from '../../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../../global';\n\nimport { ApiChatFolder } from '../../../api/types';\nimport { SettingsScreens } from '../../../types';\nimport { FolderEditDispatch } from '../../../hooks/reducers/useFoldersReducer';\n\nimport { ALL_FOLDER_ID } from '../../../config';\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { captureEvents, SwipeDirection } from '../../../util/captureEvents';\nimport buildClassName from '../../../util/buildClassName';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useLang from '../../../hooks/useLang';\nimport useHistoryBack from '../../../hooks/useHistoryBack';\n\nimport Transition from '../../ui/Transition';\nimport TabList from '../../ui/TabList';\nimport ChatList from './ChatList';\nimport { useFolderManagerForUnreadCounters } from '../../../hooks/useFolderManager';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n foldersDispatch: FolderEditDispatch;\n};\n\ntype StateProps = {\n chatFoldersById: Record;\n orderedFolderIds?: number[];\n activeChatFolder: number;\n currentUserId?: string;\n lastSyncTime?: number;\n shouldSkipHistoryAnimations?: boolean;\n};\n\nconst SAVED_MESSAGES_HOTKEY = '0';\n\nconst ChatFolders: FC = ({\n foldersDispatch,\n onScreenSelect,\n chatFoldersById,\n orderedFolderIds,\n activeChatFolder,\n currentUserId,\n lastSyncTime,\n shouldSkipHistoryAnimations,\n}) => {\n const {\n loadChatFolders,\n setActiveChatFolder,\n openChat,\n } = getActions();\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 = useFolderManagerForUnreadCounters();\n const folderTabs = useMemo(() => {\n if (!displayedFolders || !displayedFolders.length) {\n return undefined;\n }\n\n return [\n {\n id: ALL_FOLDER_ID,\n title: lang.code === 'en' ? 'All' : lang('FilterAllChats'),\n },\n ...displayedFolders.map(({ id, title }) => ({\n id,\n title,\n badgeCount: folderCountersById[id]?.chatsCount,\n isBadgeActive: Boolean(folderCountersById[id]?.notificationsCount),\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 chatFolders: {\n byId: chatFoldersById,\n orderedIds: orderedFolderIds,\n activeChatFolder,\n },\n currentUserId,\n lastSyncTime,\n shouldSkipHistoryAnimations,\n } = global;\n\n return {\n chatFoldersById,\n orderedFolderIds,\n activeChatFolder,\n currentUserId,\n lastSyncTime,\n shouldSkipHistoryAnimations,\n };\n },\n)(ChatFolders));\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, 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\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 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, memo, useCallback, useEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { LeftColumnContent, SettingsScreens } from '../../../types';\nimport { FolderEditDispatch } from '../../../hooks/reducers/useFoldersReducer';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\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 ChatFolders from './ChatFolders';\nimport LeftSearch from '../search/LeftSearch.async';\nimport ContactList from './ContactList.async';\nimport NewChatButton from '../NewChatButton';\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\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}) => {\n const [isNewChatButtonShown, setIsNewChatButtonShown] = useState(IS_TOUCH_ENV);\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 {(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 memo(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 { getActions, withGlobal } from '../../global';\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 } = getActions();\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 case SettingsScreens.QuickReaction:\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 function 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 function handleMouseUp() {\n document.body.classList.remove('cursor-ew-resize');\n }\n\n function initResize(e: React.MouseEvent) {\n e.preventDefault();\n\n document.body.classList.add('cursor-ew-resize');\n\n setInitialMouseX(e.clientX);\n setInitialElementWidth(elementRef.current!.offsetWidth);\n markIsActive();\n }\n\n function resetResize(e: React.MouseEvent) {\n e.preventDefault();\n elementRef.current!.style.width = '';\n onReset();\n }\n\n useEffect(() => {\n if (!isActive) return undefined;\n\n const handleMouseMove = (e: MouseEvent) => {\n const newWidth = Math.ceil(initialElementWidth + e.clientX - initialMouseX);\n elementRef.current!.style.width = `${newWidth}px`;\n };\n\n function stopDrag() {\n cleanup();\n onResize(elementRef.current!.offsetWidth);\n }\n\n function cleanup() {\n handleMouseUp();\n document.removeEventListener('mousemove', handleMouseMove, false);\n document.removeEventListener('mouseup', stopDrag, false);\n document.removeEventListener('blur', stopDrag, false);\n unmarkIsActive();\n }\n\n document.addEventListener('mousemove', handleMouseMove, false);\n document.addEventListener('mouseup', stopDrag, false);\n document.addEventListener('blur', stopDrag, false);\n\n return cleanup;\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\nconst useCustomBackground = (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\nexport default useCustomBackground;\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\nconst useWindowSize = () => {\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\nexport default useWindowSize;\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 { getActions, withGlobal } from '../../global';\n\nimport { MessageListType } from '../../global/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\nimport { IAnchorPosition, ManagementScreens } 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 '../../global/helpers';\nimport {\n selectChat,\n selectChatBot,\n selectIsUserBlocked,\n selectIsChatBotNotStarted,\n selectIsChatWithSelf,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n} from '../../global/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 canViewStatistics?: boolean;\n canLeave?: boolean;\n canEnterVoiceChat?: boolean;\n canCreateVoiceChat?: boolean;\n pendingJoinRequests?: number;\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 canViewStatistics,\n canLeave,\n canEnterVoiceChat,\n canCreateVoiceChat,\n pendingJoinRequests,\n isRightColumnShown,\n canExpandActions,\n}) => {\n const {\n joinChannel,\n sendBotCommand,\n openLocalTextSearch,\n restartBot,\n openCallFallbackConfirm,\n requestNextManagementScreen,\n } = getActions();\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 handleJoinRequestsClick = useCallback(() => {\n requestNextManagementScreen({ screen: ManagementScreens.JoinRequests });\n }, [requestNextManagementScreen]);\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 {Boolean(pendingJoinRequests) && (\n \n \n
{pendingJoinRequests}
\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 const canViewStatistics = chat.fullInfo?.canViewStatistics;\n const pendingJoinRequests = chat.fullInfo?.requestsPending;\n\n return {\n noMenu: false,\n isChannel,\n isRightColumnShown,\n canStartBot,\n canRestartBot,\n canSubscribe,\n canSearch,\n canCall,\n canMute,\n canViewStatistics,\n canLeave,\n canEnterVoiceChat,\n canCreateVoiceChat,\n pendingJoinRequests,\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 '../global/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 } from '../../global/helpers';\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';\nimport { renderMessageSummary } from '../common/helpers/renderMessageText';\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 = renderMessageSummary(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

{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) => {\n if (!blob) throw new Error('Image resize failed!');\n return URL.createObjectURL(blob);\n })\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) => {\n if (!blob) throw new Error('Image resize failed!');\n return URL.createObjectURL(blob);\n })\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): Promise {\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 '../global/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\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\nconst useMessageMediaMetadata = (\n message: ApiMessage, sender?: ApiUser | ApiChat, chat?: ApiChat,\n): 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\nexport default useMessageMediaMetadata;\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 { getActions, withGlobal } from '../../global';\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 '../../global/helpers';\nimport { selectChat, selectSender } from '../../global/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 } = getActions();\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 { getActions, withGlobal } from '../../../global';\n\nimport { ApiChat, ApiGroupCall, ApiUser } from '../../../api/types';\n\nimport { selectChatGroupCall } from '../../../global/selectors/calls';\nimport buildClassName from '../../../util/buildClassName';\nimport { selectChat } from '../../../global/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 } = getActions();\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, memo, useCallback, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal, getActions } from '../../global';\n\nimport { ApiChat, ApiChatSettings, ApiUser } from '../../api/types';\n\nimport { selectChat, selectUser } from '../../global/selectors';\nimport {\n getChatTitle, getUserFirstOrLastName, getUserFullName, isChatBasicGroup, isUserId,\n} from '../../global/helpers';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\nimport useFlag from '../../hooks/useFlag';\n\nimport Button from '../ui/Button';\nimport ConfirmDialog from '../ui/ConfirmDialog';\nimport Checkbox from '../ui/Checkbox';\n\nimport './ChatReportPanel.scss';\n\ntype OwnProps = {\n chatId: string;\n className?: string;\n settings?: ApiChatSettings;\n};\n\ntype StateProps = {\n currentUserId?: string;\n chat?: ApiChat;\n user?: ApiUser;\n};\n\nconst ChatReportPanel: FC = ({\n chatId, className, chat, user, settings, currentUserId,\n}) => {\n const {\n openAddContactDialog,\n blockContact,\n reportSpam,\n deleteChat,\n leaveChannel,\n deleteChatUser,\n deleteHistory,\n toggleChatArchived,\n hideChatReportPanel,\n } = getActions();\n\n const lang = useLang();\n const [isBlockUserModalOpen, openBlockUserModal, closeBlockUserModal] = useFlag();\n const [shouldReportSpam, setShouldReportSpam] = useState(true);\n const [shouldDeleteChat, setShouldDeleteChat] = useState(true);\n const { accessHash } = chat || {};\n const {\n isAutoArchived, canReportSpam, canAddContact, canBlockContact,\n } = settings || {};\n const isBasicGroup = chat && isChatBasicGroup(chat);\n\n const handleAddContact = useCallback(() => {\n openAddContactDialog({ userId: chatId });\n if (isAutoArchived) {\n toggleChatArchived({ chatId });\n }\n }, [openAddContactDialog, isAutoArchived, toggleChatArchived, chatId]);\n\n const handleConfirmBlock = useCallback(() => {\n closeBlockUserModal();\n blockContact({ contactId: chatId, accessHash });\n if (canReportSpam && shouldReportSpam) {\n reportSpam({ chatId });\n }\n if (shouldDeleteChat) {\n deleteChat({ chatId });\n }\n }, [\n accessHash, blockContact, closeBlockUserModal, deleteChat, reportSpam, canReportSpam, shouldDeleteChat,\n shouldReportSpam, chatId,\n ]);\n\n const handleCloseReportPanel = useCallback(() => {\n hideChatReportPanel({ chatId });\n }, [chatId, hideChatReportPanel]);\n\n const handleChatReportSpam = useCallback(() => {\n closeBlockUserModal();\n reportSpam({ chatId });\n if (isBasicGroup) {\n deleteChatUser({ chatId, userId: currentUserId });\n deleteHistory({ chatId, shouldDeleteForAll: false });\n } else {\n leaveChannel({ chatId });\n }\n }, [\n chatId, closeBlockUserModal, currentUserId, deleteChatUser, deleteHistory, isBasicGroup, leaveChannel, reportSpam,\n ]);\n\n if (!settings) {\n return undefined;\n }\n\n return (\n
\n {canAddContact && (\n \n {lang('lng_new_contact_add')}\n \n )}\n {canBlockContact && (\n \n {lang('lng_new_contact_block')}\n \n )}\n {canReportSpam && !canBlockContact && (\n \n {lang('lng_report_spam_and_leave')}\n \n )}\n \n \n \n \n {user && canReportSpam && (\n \n )}\n {user && (\n \n )}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => ({\n currentUserId: global.currentUserId,\n chat: selectChat(global, chatId),\n user: isUserId(chatId) ? selectUser(global, chatId) : undefined,\n }),\n)(ChatReportPanel));\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../global';\nimport cycleRestrict from '../../util/cycleRestrict';\n\nimport { GlobalState, MessageListType } from '../../global/types';\nimport {\n ApiChat, ApiMessage, ApiTypingStatus, ApiUser, MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport {\n EDITABLE_INPUT_ID,\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n SAFE_SCREEN_WIDTH_FOR_CHAT_INFO,\n SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n} from '../../config';\nimport { IS_SINGLE_COLUMN_LAYOUT, IS_TABLET_COLUMN_LAYOUT } from '../../util/environment';\nimport {\n getChatTitle, getMessageKey, getSenderTitle, isUserId,\n} from '../../global/helpers';\nimport {\n selectAllowedMessageActions,\n selectChat,\n selectChatMessage,\n selectChatMessages,\n selectForwardedSender,\n selectIsChatWithBot,\n selectIsChatWithSelf,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n selectPinnedIds,\n selectScheduledIds,\n selectThreadInfo,\n selectThreadTopMessageId,\n} from '../../global/selectors';\nimport useEnsureMessage from '../../hooks/useEnsureMessage';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\nimport useConnectionStatus from '../../hooks/useConnectionStatus';\n\nimport PrivateChatInfo from '../common/PrivateChatInfo';\nimport GroupChatInfo from '../common/GroupChatInfo';\nimport UnreadCounter from '../common/UnreadCounter';\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';\nimport ChatReportPanel from './ChatReportPanel';\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 messagesCount?: number;\n isChatWithSelf?: boolean;\n isChatWithBot?: boolean;\n lastSyncTime?: number;\n shouldSkipHistoryAnimations?: boolean;\n currentTransitionKey: number;\n connectionState?: GlobalState['connectionState'];\n isSyncing?: GlobalState['isSyncing'];\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 messagesCount,\n isChatWithSelf,\n isChatWithBot,\n lastSyncTime,\n shouldSkipHistoryAnimations,\n currentTransitionKey,\n connectionState,\n isSyncing,\n}) => {\n const {\n openChatWithInfo,\n pinMessage,\n focusMessage,\n openChat,\n openPreviousChat,\n loadPinnedMessages,\n toggleLeftColumn,\n exitMessageSelectMode,\n } = getActions();\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 const { settings } = chat || {};\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 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 hasChatSettings = Boolean(settings?.canAddContact || settings?.canBlockContact || settings?.canReportSpam);\n const {\n shouldRender: shouldShowChatReportPanel,\n transitionClassNames: chatReportPanelClassNames,\n } = useShowTransition(hasChatSettings);\n const renderingChatSettings = useCurrentOrPrev(hasChatSettings ? settings : undefined, true);\n\n const {\n shouldRender: shouldRenderAudioPlayer,\n transitionClassNames: audioPlayerClassNames,\n } = useShowTransition(Boolean(audioMessage));\n\n const renderingAudioMessage = useCurrentOrPrev(audioMessage, true);\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 { connectionStatusText } = useConnectionStatus(lang, connectionState, isSyncing, true);\n\n function renderInfo() {\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, withUnreadCounter = false) {\n return (\n
\n \n
\n \n {withUnreadCounter && }\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 {shouldShowChatReportPanel && (\n \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 chat = selectChat(global, chatId);\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 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 isSyncing: global.isSyncing,\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 { getDayStartAt } from '../../../util/dateFormat';\nimport { isActionMessage } from '../../../global/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: getDayStartAt(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 = getDayStartAt(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 { getActions } from '../../../global';\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 } = getActions();\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 '../../../../global/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 hasReactions,\n isGeoLiveActive,\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 hasReactions?: boolean;\n isGeoLiveActive?: boolean;\n } = {},\n) {\n const {\n text, photo, video, audio, voice, document, poll, webPage, contact, location,\n } = getMessageContent(message);\n\n const classNames = ['message-content'];\n const isMedia = photo || video || location;\n const hasText = text || location?.type === 'venue' || isGeoLiveActive;\n const isMediaWithNoText = isMedia && !hasText;\n const isViaBot = Boolean(message.viaBotId);\n\n if (isEmojiOnlyMessage(customShape)) {\n classNames.push(`emoji-only emoji-only-${customShape}`);\n } else if (hasText) {\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 (isMedia) {\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 (hasReactions) {\n classNames.push('has-reactions');\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 || (location && !hasText) || !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 '../../../../global/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 { RefObject } from 'react';\nimport React, { useEffect, useRef } from '../../../../lib/teact/teact';\nimport { getActions } from '../../../../global';\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';\nimport { REM } from '../../../common/helpers/mediaDimensions';\n\nconst ANDROID_KEYBOARD_HIDE_DELAY_MS = 350;\nconst SWIPE_ANIMATION_DURATION = 150;\nconst QUICK_REACTION_DOUBLE_TAP_DELAY = 200;\nconst QUICK_REACTION_AREA_WIDTH = 3 * REM;\nconst QUICK_REACTION_AREA_HEIGHT = Number(REM);\nconst GROUP_MESSAGE_HOVER_ATTRIBUTE = 'data-is-document-group-hover';\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 chatId: string,\n isContextMenuShown: boolean,\n contentRef: RefObject,\n isOwn: boolean,\n shouldHandleMouseLeave: boolean,\n) {\n const { setReplyingToId, sendDefaultReaction } = getActions();\n\n const [isQuickReactionVisible, markQuickReactionVisible, unmarkQuickReactionVisible] = useFlag();\n const [isSwiped, markSwiped, unmarkSwiped] = useFlag();\n const doubleTapTimeoutRef = useRef();\n\n function handleMouseDown(e: React.MouseEvent) {\n preventMessageInputBlur(e);\n handleBeforeContextMenu(e);\n }\n\n function handleMouseMove(e: React.MouseEvent) {\n const container = contentRef.current;\n if (!container) return;\n\n const { clientX, clientY } = e;\n const {\n x, width, y, height,\n } = container.getBoundingClientRect();\n\n const isVisibleX = Math.abs((isOwn ? (clientX - x) : (x + width - clientX))) < QUICK_REACTION_AREA_WIDTH;\n const isVisibleY = Math.abs(y + height - clientY) < QUICK_REACTION_AREA_HEIGHT;\n if (isVisibleX && isVisibleY) {\n markQuickReactionVisible();\n } else {\n unmarkQuickReactionVisible();\n }\n }\n\n function handleSendQuickReaction(e: React.MouseEvent) {\n const { x, y } = e.currentTarget.getBoundingClientRect();\n sendDefaultReaction({\n chatId,\n messageId,\n x,\n y,\n });\n }\n\n function handleTap(e: React.MouseEvent) {\n 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 handleDoubleTap(e: React.MouseEvent) {\n const { pageX: x, pageY: y } = e;\n\n sendDefaultReaction({\n chatId,\n messageId,\n x,\n y,\n });\n }\n\n function handleClick(e: React.MouseEvent) {\n if (isInSelectMode) {\n selectMessage(e);\n return;\n }\n\n if (!IS_TOUCH_ENV) return;\n\n if (doubleTapTimeoutRef.current) {\n clearInterval(doubleTapTimeoutRef.current);\n doubleTapTimeoutRef.current = undefined;\n handleDoubleTap(e);\n return;\n }\n\n doubleTapTimeoutRef.current = setTimeout(() => {\n doubleTapTimeoutRef.current = undefined;\n handleTap(e);\n }, QUICK_REACTION_DOUBLE_TAP_DELAY);\n }\n\n function handleContextMenu(e: React.MouseEvent) {\n if (IS_ANDROID) {\n if ((e.target as HTMLElement).matches('a[href]') || isContextMenuShown) {\n return;\n }\n\n e.preventDefault();\n selectMessage();\n } else {\n onContextMenu(e);\n }\n }\n\n function handleContainerDoubleClick() {\n if (IS_TOUCH_ENV) return;\n\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 || isContextMenuShown) {\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 }, [\n containerRef, isInSelectMode, messageId, setReplyingToId, markSwiped, unmarkSwiped, canReply, isContextMenuShown,\n ]);\n\n function handleMouseLeave(e: React.MouseEvent) {\n unmarkQuickReactionVisible();\n if (shouldHandleMouseLeave) handleDocumentGroupMouseLeave(e);\n }\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 handleMouseMove,\n handleSendQuickReaction,\n handleMouseLeave,\n isSwiped,\n isQuickReactionVisible,\n handleDocumentGroupMouseEnter,\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","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 '../../global';\n\nimport { ApiUser, ApiMessage, ApiChat } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport {\n selectUser,\n selectChatMessage,\n selectIsMessageFocused,\n selectChat,\n} from '../../global/selectors';\nimport { getMessageHtmlId, isChatChannel } from '../../global/helpers';\nimport buildClassName from '../../util/buildClassName';\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 senderUser?: ApiUser;\n senderChat?: 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 senderUser,\n senderChat,\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 senderUser,\n senderChat,\n targetUsers,\n targetMessage,\n targetChatId,\n { asTextWithSpoilers: isEmbedded },\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 {content};\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 isChat = chat && (isChatChannel(chat) || userId === message.chatId);\n const senderUser = !isChat && userId ? selectUser(global, userId) : undefined;\n const senderChat = isChat ? chat : undefined;\n\n return {\n usersById,\n senderUser,\n senderChat,\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 getSenderTitle,\n getMessageRoundVideo,\n} from '../../global/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';\nimport { renderMessageSummary } from './helpers/renderMessageText';\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 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(mediaThumbnail, mediaBlobUrl, isRoundVideo, isProtected)}\n
\n

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

\n
{renderText(senderTitle || title || NBSP)}
\n
\n \n );\n};\n\nfunction renderPictogram(\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, { FC, memo, useCallback } from '../../../lib/teact/teact';\nimport { getActions } from '../../../global';\n\nimport { ActiveReaction } from '../../../global/types';\nimport { ApiAvailableReaction, ApiMediaFormat } from '../../../api/types';\n\nimport buildClassName from '../../../util/buildClassName';\nimport useMedia from '../../../hooks/useMedia';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useFlag from '../../../hooks/useFlag';\n\nimport ReactionStaticEmoji from '../../common/ReactionStaticEmoji';\nimport AnimatedSticker from '../../common/AnimatedSticker';\n\nimport './ReactionAnimatedEmoji.scss';\n\ntype OwnProps = {\n reaction: string;\n activeReaction?: ActiveReaction;\n isInMeta?: boolean;\n availableReactions?: ApiAvailableReaction[];\n};\n\nconst CENTER_ICON_SIZE = 30;\nconst EFFECT_SIZE = 100;\n\nconst ReactionAnimatedEmoji: FC = ({\n reaction,\n activeReaction,\n isInMeta,\n availableReactions,\n}) => {\n const { stopActiveReaction } = getActions();\n\n const availableReaction = availableReactions?.find((r) => r.reaction === reaction);\n const centerIconId = availableReaction?.centerIcon?.id;\n const effectId = availableReaction?.aroundAnimation?.id;\n const mediaDataCenterIcon = useMedia(`sticker${centerIconId}`, !centerIconId, ApiMediaFormat.Lottie);\n const mediaDataEffect = useMedia(`sticker${effectId}`, !effectId, ApiMediaFormat.Lottie);\n\n const shouldPlay = Boolean(activeReaction?.reaction === reaction && mediaDataCenterIcon && mediaDataEffect);\n const {\n shouldRender: shouldRenderAnimation,\n transitionClassNames: animationClassNames,\n } = useShowTransition(shouldPlay, undefined, true, 'slow');\n\n const handleEnded = useCallback(() => {\n stopActiveReaction({ messageId: activeReaction?.messageId, reaction });\n }, [activeReaction?.messageId, reaction, stopActiveReaction]);\n\n const [isAnimationLoaded, markAnimationLoaded, unmarkAnimationLoaded] = useFlag();\n const shouldRenderStatic = !shouldPlay || !isAnimationLoaded;\n\n const className = buildClassName(\n 'ReactionAnimatedEmoji',\n isInMeta && 'in-meta',\n shouldRenderAnimation && 'is-animating',\n );\n\n return (\n
\n {shouldRenderStatic && }\n {shouldRenderAnimation && (\n <>\n \n \n \n )}\n
\n );\n};\n\nexport default memo(ReactionAnimatedEmoji);\n","import React, {\n FC, memo, useMemo,\n} from '../../../lib/teact/teact';\n\nimport { ApiAvailableReaction, ApiMessage, ApiMessageOutgoingStatus } from '../../../api/types';\nimport { ActiveReaction } from '../../../global/types';\n\nimport { formatDateTimeToString, formatTime } from '../../../util/dateFormat';\nimport { formatIntegerCompact } from '../../../util/textFormat';\n\nimport renderText from '../../common/helpers/renderText';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\nimport buildClassName from '../../../util/buildClassName';\n\nimport MessageOutgoingStatus from '../../common/MessageOutgoingStatus';\nimport ReactionAnimatedEmoji from './ReactionAnimatedEmoji';\n\nimport './MessageMeta.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n reactionMessage?: ApiMessage;\n withReactions?: boolean;\n withReactionOffset?: boolean;\n outgoingStatus?: ApiMessageOutgoingStatus;\n signature?: string;\n onClick: (e: React.MouseEvent) => void;\n activeReaction?: ActiveReaction;\n availableReactions?: ApiAvailableReaction[];\n};\n\nconst MessageMeta: FC = ({\n message, outgoingStatus, signature, onClick, withReactions,\n activeReaction, withReactionOffset, availableReactions,\n reactionMessage,\n}) => {\n const lang = useLang();\n const [isActivated, markActivated] = useFlag();\n\n const reactions = withReactions && reactionMessage?.reactions?.results.filter((l) => l.count > 0);\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 {reactions && reactions.map((l) => (\n \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(lang, message.date * 1000)}\n \n {outgoingStatus && (\n \n )}\n
\n );\n};\n\nexport default memo(MessageMeta);\n","import React, { FC, useEffect, useRef } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { NO_STICKER_SET_ID } from '../../../config';\nimport { getStickerDimensions } from '../../common/helpers/mediaDimensions';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../global/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';\nimport safePlay from '../../../util/safePlay';\nimport { IS_WEBM_SUPPORTED } from '../../../util/environment';\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 { isLottie, stickerSetId, isVideo } = sticker;\n const canDisplayVideo = IS_WEBM_SUPPORTED;\n const isMemojiSticker = stickerSetId === NO_STICKER_SET_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 previewMediaHash = isVideo && !canDisplayVideo && (\n sticker.isPreloadedGlobally ? `sticker${sticker.id}?size=m` : getMessageMediaHash(message, 'pictogram'));\n const previewBlobUrl = useMedia(previewMediaHash);\n const thumbDataUri = useWebpThumbnail(message);\n const previewUrl = previewBlobUrl || thumbDataUri;\n\n const mediaData = useMedia(\n mediaHash,\n !shouldLoad,\n getMessageMediaFormat(message, 'inline'),\n lastSyncTime,\n );\n\n const isMediaLoaded = Boolean(mediaData);\n const [isLottieLoaded, markLottieLoaded] = useFlag(isMediaLoaded);\n const isMediaReady = isLottie ? isLottieLoaded : 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 useEffect(() => {\n if (!isVideo || !ref.current) return;\n const video = ref.current.querySelector('video');\n if (!video) return;\n if (shouldPlay) {\n safePlay(video);\n } else {\n video.pause();\n }\n }, [isVideo, shouldPlay]);\n\n return (\n
\n {(!isMediaReady || (isVideo && !canDisplayVideo)) && (\n \n )}\n {!isLottie && !isVideo && (\n \n )}\n {isVideo && canDisplayVideo && isMediaReady && (\n \n )}\n {isLottie && 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 '../../../../global/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 { CUSTOM_APPENDIX_ATTRIBUTE } from '../../../config';\nimport {\n getMessagePhoto,\n getMessageWebPagePhoto,\n getMessageMediaHash,\n getMediaTransferState,\n isOwnMessage,\n} from '../../../global/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 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 { getActions } from '../../../global';\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 '../../../global/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 getActions().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 { getActions, withGlobal } from '../../../global';\n\nimport { ApiUser, ApiContact, ApiCountryCode } from '../../../api/types';\n\nimport { selectUser } from '../../../global/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 { openChat } = getActions();\n\n const {\n firstName,\n lastName,\n phoneNumber,\n userId,\n } = contact;\n\n const handleClick = useCallback(() => {\n openChat({ id: userId });\n }, [openChat, 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 { getActions, withGlobal } from '../../../global';\n\nimport {\n ApiMessage, ApiPoll, ApiUser, ApiPollAnswer,\n} from '../../../api/types';\n\nimport renderText from '../../common/helpers/renderText';\nimport { renderTextWithEntities } from '../../common/helpers/renderTextWithEntities';\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 } = getActions();\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 '../../../global/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 '../../../global/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","const PROVIDER = 'http://maps.google.com/maps';\n\n// eslint-disable-next-line max-len\n// https://github.com/TelegramMessenger/Telegram-iOS/blob/2a32c871882c4e1b1ccdecd34fccd301723b30d9/submodules/LocationResources/Sources/VenueIconResources.swift#L82\nconst VENUE_COLORS = new Map(Object.entries({\n 'building/medical': '#43b3f4',\n 'building/gym': '#43b3f4',\n 'education/cafeteria': '#f7943f',\n 'travel/bedandbreakfast': '#9987ff',\n 'travel/hotel': '#9987ff',\n 'travel/hostel': '#9987ff',\n 'travel/resort': '#9987ff',\n 'travel/hotel_bar': '#e56dd6',\n arts_entertainment: '#e56dd6',\n building: '#6e81b2',\n education: '#a57348',\n event: '#959595',\n food: '#f7943f',\n home: '#00aeef',\n nightlife: '#e56dd6',\n parks_outdoors: '#6cc039',\n shops: '#ffb300',\n travel: '#1c9fff',\n work: '#ad7854',\n}));\n\nconst RANDOM_COLORS = [\n '#e56cd5', '#f89440', '#9986ff', '#44b3f5', '#6dc139', '#ff5d5a', '#f87aad', '#6e82b3', '#f5ba21',\n];\n\nexport function prepareMapUrl(lat: number, long: number, zoom: number) {\n return `${PROVIDER}/place/${lat}+${long}/@${lat},${long},${zoom}z`;\n}\n\nexport function getMetersPerPixel(lat: number, zoom: number) {\n // https://groups.google.com/g/google-maps-js-api-v3/c/hDRO4oHVSeM/m/osOYQYXg2oUJ\n return (156543.03392 * Math.cos(lat * (Math.PI / 180))) / 2 ** zoom;\n}\n\nexport function getVenueIconUrl(type?: string) {\n if (!type) return '';\n return `https://ss3.4sqi.net/img/categories_v2/${type}_88.png`;\n}\n\n// eslint-disable-next-line max-len\n// https://github.com/TelegramMessenger/Telegram-iOS/blob/2a32c871882c4e1b1ccdecd34fccd301723b30d9/submodules/LocationResources/Sources/VenueIconResources.swift#L104\nexport function getVenueColor(type?: string) {\n if (!type) return '#008df2';\n return VENUE_COLORS.get(type)\n || VENUE_COLORS.get(type.split('/')[0])\n || RANDOM_COLORS[stringToNumber(type) % RANDOM_COLORS.length];\n}\n\nfunction stringToNumber(str: string) {\n return str.split('').reduce((prevHash, currVal) => (\n // eslint-disable-next-line no-bitwise\n (((prevHash << 5) - prevHash) + currVal.charCodeAt(0)) | 0), 0);\n}\n","import React, { FC } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Skeleton.scss';\n\ntype OwnProps = {\n variant?: 'rectangular' | 'rounded-rect' | 'round';\n animation?: 'wave' | 'pulse';\n width?: number;\n height?: number;\n className?: string;\n};\n\nconst Skeleton: FC = ({\n variant = 'rectangular', animation = 'wave', width, height, className,\n}) => {\n const classNames = buildClassName('Skeleton', variant, animation, className);\n const style = (width ? `width: ${width}px;` : '') + (height ? `height: ${height}px;` : '');\n return (\n
\n );\n};\n\nexport default Skeleton;\n","import React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiChat, ApiMessage, ApiUser } from '../../../api/types';\nimport { ISettings } from '../../../types';\n\nimport { CUSTOM_APPENDIX_ATTRIBUTE } from '../../../config';\nimport {\n getMessageLocation,\n buildStaticMapHash,\n isGeoLiveExpired,\n isOwnMessage,\n isUserId,\n} from '../../../global/helpers';\nimport useMedia from '../../../hooks/useMedia';\nimport getCustomAppendixBg from './helpers/getCustomAppendixBg';\nimport { formatCountdownShort, formatLastUpdated } from '../../../util/dateFormat';\nimport useLang from '../../../hooks/useLang';\nimport useForceUpdate from '../../../hooks/useForceUpdate';\nimport useTimeout from '../../../hooks/useTimeout';\nimport {\n getMetersPerPixel, getVenueColor, getVenueIconUrl, prepareMapUrl,\n} from '../../../util/map';\nimport buildClassName from '../../../util/buildClassName';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useInterval from '../../../hooks/useInterval';\nimport { getServerTime } from '../../../util/serverTime';\n\nimport Avatar from '../../common/Avatar';\nimport Skeleton from '../../ui/Skeleton';\n\nimport mapPin from '../../../assets/map-pin.svg';\nimport './Location.scss';\n\nconst MOVE_THRESHOLD = 0.0001; // ~11m\nconst DEFAULT_MAP_CONFIG = {\n width: 400,\n height: 300,\n zoom: 16,\n scale: 2,\n};\n\n// eslint-disable-next-line max-len\nconst SVG_PIN = { __html: '' };\n\ntype OwnProps = {\n message: ApiMessage;\n peer?: ApiUser | ApiChat;\n lastSyncTime?: number;\n isInSelectMode?: boolean;\n isSelected?: boolean;\n theme: ISettings['theme'];\n serverTimeOffset: number;\n};\n\nconst Location: FC = ({\n message,\n peer,\n lastSyncTime,\n isInSelectMode,\n isSelected,\n theme,\n serverTimeOffset,\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 countdownRef = useRef(null);\n const lang = useLang();\n const forceUpdate = useForceUpdate();\n\n const location = getMessageLocation(message)!;\n const { type, geo } = location;\n\n const serverTime = getServerTime(serverTimeOffset);\n const isExpired = isGeoLiveExpired(message, serverTime);\n const secondsBeforeEnd = (type === 'geoLive' && !isExpired) ? message.date + location.period - serverTime\n : undefined;\n\n const [point, setPoint] = useState(geo);\n\n const shouldRenderText = type === 'venue' || (type === 'geoLive' && !isExpired);\n const {\n width, height, zoom, scale,\n } = DEFAULT_MAP_CONFIG;\n\n const mediaHash = Boolean(lastSyncTime) && buildStaticMapHash(point, width, height, zoom, scale);\n const mediaBlobUrl = useMedia(mediaHash);\n const prevMediaBlobUrl = usePrevious(mediaBlobUrl);\n const mapBlobUrl = mediaBlobUrl || prevMediaBlobUrl;\n\n const isPeerUser = peer && isUserId(peer.id);\n const avatarUser = (peer && isPeerUser) ? peer as ApiUser : undefined;\n const avatarChat = (peer && !isPeerUser) ? peer as ApiChat : undefined;\n\n const isOwn = isOwnMessage(message);\n\n const accuracyRadiusPx = useMemo(() => {\n if (type !== 'geoLive' || !point.accuracyRadius) {\n return 0;\n }\n\n const { lat, accuracyRadius } = point;\n return accuracyRadius / getMetersPerPixel(lat, zoom);\n }, [type, point, zoom]);\n\n const handleClick = () => {\n const url = prepareMapUrl(point.lat, point.long, zoom);\n window.open(url, '_blank')?.focus();\n };\n\n const updateCountdown = useCallback((countdownEl: HTMLDivElement) => {\n if (type !== 'geoLive') return;\n const radius = 12;\n const circumference = radius * 2 * Math.PI;\n const svgEl = countdownEl.lastElementChild;\n const timerEl = countdownEl.firstElementChild as SVGElement;\n\n const timeLeft = message.date + location.period - getServerTime(serverTimeOffset);\n const strokeDashOffset = (1 - timeLeft / location.period) * circumference;\n const text = formatCountdownShort(lang, timeLeft * 1000);\n\n if (!svgEl || !timerEl) {\n countdownEl.innerHTML = `\n ${text}\n \n \n `;\n } else {\n timerEl.textContent = text;\n svgEl.firstElementChild!.setAttribute('stroke-dashoffset', `-${strokeDashOffset}`);\n }\n }, [type, message.date, location, serverTimeOffset, lang]);\n\n useLayoutEffect(() => {\n if (countdownRef.current) {\n updateCountdown(countdownRef.current);\n }\n }, [updateCountdown]);\n\n useLayoutEffect(() => {\n if (shouldRenderText) return;\n const contentEl = ref.current!.closest('.message-content')!;\n if (mapBlobUrl) {\n getCustomAppendixBg(mapBlobUrl, isOwn, isInSelectMode, isSelected, theme).then((appendixBg) => {\n contentEl.style.setProperty('--appendix-bg', appendixBg);\n contentEl.classList.add('has-appendix-thumb');\n contentEl.setAttribute(CUSTOM_APPENDIX_ATTRIBUTE, '');\n });\n }\n }, [isOwn, isInSelectMode, isSelected, theme, mapBlobUrl, shouldRenderText]);\n\n useEffect(() => {\n // Prevent map refetching for slight location changes\n if (Math.abs(geo.lat - point.lat) < MOVE_THRESHOLD && Math.abs(geo.long - point.long) < MOVE_THRESHOLD) {\n if (point.accuracyRadius !== geo.accuracyRadius) {\n setPoint({\n ...point,\n accuracyRadius: geo.accuracyRadius,\n });\n }\n return;\n }\n setPoint(geo);\n }, [geo, point]);\n\n useTimeout(() => {\n forceUpdate();\n }, !isExpired ? (secondsBeforeEnd || 0) * 1000 : undefined);\n\n useInterval(() => {\n const countdownEl = countdownRef.current;\n\n if (countdownEl) {\n updateCountdown(countdownEl);\n }\n }, secondsBeforeEnd ? 1000 : undefined);\n\n function renderInfo() {\n if (!shouldRenderText) return undefined;\n if (type === 'venue') {\n return (\n
\n
\n {location.title}\n
\n
\n {location.address}\n
\n
\n );\n }\n if (type === 'geoLive') {\n return (\n
\n
{lang('AttachLiveLocation')}
\n
\n {formatLastUpdated(lang, serverTime, message.editDate)}\n
\n {!isExpired &&
}\n
\n );\n }\n return undefined;\n }\n\n function renderMap() {\n if (!mapBlobUrl) return ;\n return (\n \n );\n }\n\n function renderPin() {\n const pinClassName = buildClassName(\n 'pin',\n type,\n isExpired && 'expired',\n );\n if (type === 'geoLive') {\n return (\n
\n \n {location.heading !== undefined && (\n
\n )}\n
\n );\n }\n\n if (type === 'venue') {\n const color = getVenueColor(location.venueType);\n const icon = getVenueIconUrl(location.venueType);\n return (\n
\n \"\"\n
\n );\n }\n\n return (\n \"\"\n );\n }\n\n function renderOverlay() {\n if (!mapBlobUrl) return undefined;\n\n return (\n <>\n {Boolean(accuracyRadiusPx) && !isExpired && (\n \n )}\n {renderPin()}\n \n );\n }\n\n return (\n \n
\n {renderMap()}\n {renderOverlay()}\n
\n {renderInfo()}\n
\n );\n};\n\nexport default memo(Location);\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC,\n useCallback,\n useMemo,\n memo,\n} from '../../../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../../../global';\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 '../../../../global/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 } = getActions();\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 const { dimensions: dims, onClick } = props;\n return {\n ...props,\n isInSelectMode,\n isSelected,\n dimensions: {\n ...dims,\n x: 0,\n y: 0,\n },\n onClick: isInSelectMode ? undefined : 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, getMessageHtmlId } from '../../../global/helpers';\nimport { getActions, getGlobal, withGlobal } from '../../../global';\nimport withSelectControl from './hocs/withSelectControl';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\nimport {\n selectActiveDownloadIds,\n selectCanAutoLoadMedia,\n selectCanAutoPlayMedia,\n selectTheme,\n} from '../../../global/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 } = getActions();\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 { getActions } from '../../../global';\n\nimport { ApiMediaFormat, ApiMessage } from '../../../api/types';\n\nimport { ROUND_VIDEO_DIMENSIONS_PX } from '../../common/helpers/mediaDimensions';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../global/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 stopPrevious: NoneToVoidFunction;\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 = useCallback(() => {\n if (!playerRef.current) {\n return;\n }\n\n setIsActivated(false);\n setProgress(0);\n safePlay(playerRef.current);\n\n fastRaf(() => {\n playingProgressRef.current!.innerHTML = '';\n });\n }, []);\n\n const capturePlaying = useCallback(() => {\n stopPrevious?.();\n stopPrevious = stopPlaying;\n }, [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 getActions().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 { getActions, getGlobal } from '../../../global';\n\nimport {\n ApiChat, ApiThreadInfo, ApiUser,\n} from '../../../api/types';\n\nimport { isUserId } from '../../../global/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 } = getActions();\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, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { getActions, getGlobal } from '../../../global';\n\nimport {\n ApiAvailableReaction, ApiMessage, ApiReactionCount, ApiUser,\n} from '../../../api/types';\nimport { ActiveReaction } from '../../../global/types';\n\nimport buildClassName from '../../../util/buildClassName';\nimport { formatIntegerCompact } from '../../../util/textFormat';\n\nimport Button from '../../ui/Button';\nimport Avatar from '../../common/Avatar';\nimport ReactionAnimatedEmoji from './ReactionAnimatedEmoji';\n\nimport './Reactions.scss';\n\nconst MAX_REACTORS_AVATARS = 3;\n\nconst ReactionButton: FC<{\n reaction: ApiReactionCount;\n message: ApiMessage;\n activeReaction?: ActiveReaction;\n availableReactions?: ApiAvailableReaction[];\n}> = ({\n reaction,\n message,\n activeReaction,\n availableReactions,\n}) => {\n const { sendReaction } = getActions();\n\n const { recentReactions } = message.reactions!;\n\n const recentReactors = useMemo(() => {\n if (!recentReactions || reaction.count > MAX_REACTORS_AVATARS) {\n return undefined;\n }\n\n // No need for expensive global updates on users, so we avoid them\n const usersById = getGlobal().users.byId;\n\n return recentReactions\n .filter((recentReaction) => recentReaction.reaction === reaction.reaction)\n .map((recentReaction) => usersById[recentReaction.userId])\n .filter(Boolean) as ApiUser[];\n }, [reaction, recentReactions]);\n\n const handleClick = useCallback(() => {\n sendReaction({\n reaction: reaction.isChosen ? undefined : reaction.reaction,\n chatId: message.chatId,\n messageId: message.id,\n });\n }, [message, reaction, sendReaction]);\n\n return (\n \n \n {recentReactors?.length ? (\n
\n {recentReactors.map((user) => )}\n
\n ) : formatIntegerCompact(reaction.count)}\n \n );\n};\n\nexport default memo(ReactionButton);\n","import React, { FC, memo } from '../../../lib/teact/teact';\n\nimport { ApiAvailableReaction, ApiMessage } from '../../../api/types';\nimport { ActiveReaction } from '../../../global/types';\n\nimport buildClassName from '../../../util/buildClassName';\n\nimport ReactionButton from './ReactionButton';\n\nimport './Reactions.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n isOutside?: boolean;\n activeReaction?: ActiveReaction;\n availableReactions?: ApiAvailableReaction[];\n metaChildren?: React.ReactNode;\n};\n\nconst Reactions: FC = ({\n message,\n isOutside,\n activeReaction,\n availableReactions,\n metaChildren,\n}) => {\n return (\n
\n {message.reactions!.results.map((reaction) => (\n \n ))}\n {metaChildren}\n
\n );\n};\n\nexport default memo(Reactions);\n","import React, {\n FC, memo, useEffect, useState,\n} from '../../lib/teact/teact';\n\nimport { ActiveEmojiInteraction } from '../../global/types';\n\nimport { ObserveFn, useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport getAnimationData, { ANIMATED_STICKERS_PATHS } from './helpers/animatedAssets';\nimport useAnimatedEmoji from './hooks/useAnimatedEmoji';\n\nimport AnimatedSticker from './AnimatedSticker';\n\nconst QUALITY = 1;\n\ntype OwnProps = {\n localSticker?: string;\n localEffect?: string;\n isOwn?: boolean;\n soundId?: string;\n observeIntersection?: ObserveFn;\n size?: 'large' | 'medium' | 'small';\n lastSyncTime?: number;\n forceLoadPreview?: boolean;\n messageId?: number;\n chatId?: string;\n activeEmojiInteractions?: ActiveEmojiInteraction[];\n};\n\nconst LocalAnimatedEmoji: FC = ({\n localSticker,\n localEffect,\n isOwn,\n soundId,\n size = 'medium',\n observeIntersection,\n messageId,\n chatId,\n activeEmojiInteractions,\n}) => {\n const {\n playKey,\n ref,\n style,\n width,\n handleClick,\n markAnimationLoaded,\n } = useAnimatedEmoji(size, chatId, messageId, soundId, activeEmojiInteractions, isOwn, localEffect);\n const id = `local_emoji_${localSticker}`;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [localStickerAnimationData, setLocalStickerAnimationData] = useState();\n useEffect(() => {\n if (localSticker) {\n getAnimationData(localSticker as keyof typeof ANIMATED_STICKERS_PATHS).then((data) => {\n setLocalStickerAnimationData(data);\n });\n }\n }, [localSticker]);\n\n return (\n \n {localStickerAnimationData && (\n \n )}\n \n );\n};\n\nexport default memo(LocalAnimatedEmoji);\n","import React, {\n FC,\n memo,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n} from '../../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../../global';\n\nimport { ActiveEmojiInteraction, ActiveReaction, MessageListType } from '../../../global/types';\nimport {\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n ApiChat,\n ApiSticker,\n ApiThreadInfo,\n ApiAvailableReaction,\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 selectAnimatedEmojiEffect,\n selectAnimatedEmojiSound,\n selectMessageIdsByGroupId,\n selectLocalAnimatedEmoji,\n selectIsMessageProtected,\n selectLocalAnimatedEmojiEffect,\n selectDefaultReaction,\n} from '../../../global/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 areReactionsEmpty,\n getMessageHtmlId,\n isGeoLiveExpired,\n} from '../../../global/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';\nimport { getServerTime } from '../../../util/serverTime';\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 Location from './Location';\nimport Album from './Album';\nimport RoundVideo from './RoundVideo';\nimport InlineButtons from './InlineButtons';\nimport CommentButton from './CommentButton';\nimport Reactions from './Reactions';\nimport ReactionStaticEmoji from '../../common/ReactionStaticEmoji';\nimport LocalAnimatedEmoji from '../../common/LocalAnimatedEmoji';\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 areReactionsInMeta?: 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 canShowSender: boolean;\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 isInDocumentGroup: boolean;\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 serverTimeOffset: number;\n highlight?: string;\n isSingleEmoji?: boolean;\n animatedEmoji?: ApiSticker;\n localSticker?: string;\n localEffect?: string;\n animatedEmojiEffect?: ApiSticker;\n animatedEmojiSoundId?: string;\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 reactionMessage?: ApiMessage;\n availableReactions?: ApiAvailableReaction[];\n defaultReaction?: string;\n activeReaction?: ActiveReaction;\n activeEmojiInteractions?: ActiveEmojiInteraction[];\n};\n\ntype MetaPosition =\n 'in-text'\n | 'standalone'\n | 'none';\ntype ReactionsPosition =\n 'inside'\n | 'outside'\n | 'in-meta'\n | 'none';\n\nconst NBSP = '\\u00A0';\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 areReactionsInMeta,\n noComments,\n appearanceOrder,\n isFirstInGroup,\n isLastInGroup,\n isFirstInDocumentGroup,\n isLastInDocumentGroup,\n isLastInList,\n theme,\n forceSenderName,\n sender,\n canShowSender,\n originSender,\n botSender,\n isThreadTop,\n shouldHideReply,\n replyMessage,\n replyMessageSender,\n outgoingStatus,\n uploadProgress,\n isInDocumentGroup,\n isProtected,\n isFocused,\n focusDirection,\n noFocusHighlight,\n isResizingContainer,\n isForwarding,\n isChatWithSelf,\n isRepliesChat,\n isChannel,\n canReply,\n lastSyncTime,\n serverTimeOffset,\n highlight,\n animatedEmoji,\n localSticker,\n localEffect,\n animatedEmojiEffect,\n animatedEmojiSoundId,\n isInSelectMode,\n isSelected,\n isGroupSelected,\n threadId,\n reactionMessage,\n availableReactions,\n defaultReaction,\n activeReaction,\n activeEmojiInteractions,\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 } = getActions();\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 // eslint-disable-next-line no-null/no-null\n const contentRef = 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 {\n id: messageId, chatId, forwardInfo, viaBotId,\n } = 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 hasAnimatedEmoji = localSticker || animatedEmoji;\n const hasReactions = reactionMessage?.reactions && !areReactionsEmpty(reactionMessage.reactions);\n const asForwarded = (\n forwardInfo\n && (!isChatWithSelf || isScheduled)\n && !isRepliesChat\n && !forwardInfo.isLinkedChannelPost\n && !customShape\n );\n const isAlbum = Boolean(album) && album!.messages.length > 1;\n const isInDocumentGroupNotFirst = isInDocumentGroup && !isFirstInDocumentGroup;\n const isInDocumentGroupNotLast = isInDocumentGroup && !isLastInDocumentGroup;\n const isContextMenuShown = contextMenuPosition !== undefined;\n const canShowActionButton = (\n !(isContextMenuShown || isInSelectMode || isForwarding)\n && !isInDocumentGroupNotLast\n );\n const canForward = isChannel && !isScheduled;\n const canFocus = Boolean(isPinnedList\n || (forwardInfo\n && (forwardInfo.isChannelPost || (isChatWithSelf && !isOwn) || isRepliesChat)\n && forwardInfo.fromMessageId\n ));\n\n const withCommentButton = threadInfo && !isInDocumentGroupNotLast && messageListType === 'thread' && !noComments;\n const withQuickReactionButton = !IS_TOUCH_ENV && !isInSelectMode && defaultReaction && !isInDocumentGroupNotLast;\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 messageSender = canShowSender ? sender : undefined;\n\n const avatarPeer = forwardInfo && (isChatWithSelf || isRepliesChat || !messageSender) ? originSender : messageSender;\n const senderPeer = forwardInfo ? originSender : messageSender;\n\n const {\n handleMouseDown,\n handleClick,\n handleContextMenu,\n handleDoubleClick,\n handleContentDoubleClick,\n handleMouseMove,\n handleSendQuickReaction,\n handleMouseLeave,\n isSwiped,\n isQuickReactionVisible,\n handleDocumentGroupMouseEnter,\n } = useOuterHandlers(\n selectMessage,\n ref,\n messageId,\n isAlbum,\n Boolean(isInSelectMode),\n Boolean(canReply),\n Boolean(isProtected),\n onContextMenu,\n handleBeforeContextMenu,\n chatId,\n isContextMenuShown,\n contentRef,\n isOwn,\n isInDocumentGroupNotLast,\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 Boolean(activeReaction) && 'has-active-reaction',\n );\n\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, webPage, invoice, location,\n } = getMessageContent(message);\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 hasReactions,\n isGeoLiveActive: location?.type === 'geoLive' && !isGeoLiveExpired(message, getServerTime(serverTimeOffset)),\n });\n\n const withAppendix = contentClassName.includes('has-appendix');\n const textParts = renderMessageText(message, highlight, isEmojiOnlyMessage(customShape));\n\n let metaPosition!: MetaPosition;\n if (isInDocumentGroupNotLast) {\n metaPosition = 'none';\n } else if (textParts && !hasAnimatedEmoji && !webPage) {\n metaPosition = 'in-text';\n } else {\n metaPosition = 'standalone';\n }\n\n let reactionsPosition!: ReactionsPosition;\n if (areReactionsInMeta) {\n reactionsPosition = 'in-meta';\n } else if (hasReactions) {\n if (customShape || ((photo || video || hasAnimatedEmoji) && !textParts)) {\n reactionsPosition = 'outside';\n } else if (asForwarded) {\n metaPosition = 'standalone';\n reactionsPosition = 'inside';\n } else {\n reactionsPosition = 'inside';\n }\n } else {\n reactionsPosition = 'none';\n }\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 const signature = (isChannel && message.adminTitle) || (!asForwarded && forwardInfo?.adminTitle) || undefined;\n const metaSafeAuthorWidth = useMemo(() => {\n return signature ? calculateAuthorWidth(signature) : undefined;\n }, [signature]);\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 renderReactionsAndMeta() {\n const meta = (\n \n );\n\n if (reactionsPosition !== 'inside') {\n return meta;\n }\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 textContentClass = buildClassName(\n 'text-content',\n metaPosition === 'in-text' && '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 {localSticker && (\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 {!hasAnimatedEmoji && textParts && (\n

\n {textParts}\n {metaPosition === 'in-text' && renderReactionsAndMeta()}\n

\n )}\n\n {webPage && (\n \n )}\n {invoice && }\n {location && (\n \n )}\n
\n );\n }\n\n function renderSenderName() {\n const media = photo || video || location;\n const shouldRender = !(customShape && !viaBotId) && (\n (withSenderName && !media) || asForwarded || viaBotId || forceSenderName\n ) && !isInDocumentGroupNotFirst && !(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 && !isInDocumentGroupNotFirst && (\n
{lang('ForwardedMessage')}
\n )}\n {renderContent()}\n {!isInDocumentGroupNotLast && metaPosition === 'standalone' && renderReactionsAndMeta()}\n {canShowActionButton && canForward ? (\n \n \n \n ) : canShowActionButton && canFocus ? (\n \n \n \n ) : undefined}\n {withCommentButton && }\n {withAppendix && (\n
\n )}\n {withQuickReactionButton && (\n \n \n
\n )}\n \n {message.inlineButtons && (\n \n )}\n {reactionsPosition === 'outside' && (\n \n )}\n \n {contextMenuPosition && (\n \n )}\n \n );\n};\n\nexport default memo(withGlobal(\n (global, ownProps): StateProps => {\n const {\n focusedMessage, forwardMessages, lastSyncTime, serverTimeOffset,\n } = global;\n const {\n message, album, withSenderName, withAvatar, threadId, messageListType, isLastInDocumentGroup,\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 const isInDocumentGroup = Boolean(message.groupedId) && !message.isInAlbum;\n const documentGroupFirstMessageId = isInDocumentGroup\n ? selectMessageIdsByGroupId(global, chatId, message.groupedId!)![0]\n : undefined;\n const reactionMessage = isInDocumentGroup ? (\n isLastInDocumentGroup ? selectChatMessage(global, chatId, documentGroupFirstMessageId!) : undefined\n ) : message;\n\n const localSticker = singleEmoji ? selectLocalAnimatedEmoji(global, singleEmoji) : undefined;\n\n return {\n theme: selectTheme(global),\n chatUsername,\n forceSenderName,\n sender,\n canShowSender,\n originSender,\n botSender,\n shouldHideReply,\n isThreadTop,\n replyMessage,\n replyMessageSender,\n isInDocumentGroup,\n isProtected: selectIsMessageProtected(global, message),\n isFocused,\n isForwarding,\n reactionMessage,\n isChatWithSelf,\n isRepliesChat,\n isChannel,\n canReply,\n lastSyncTime,\n serverTimeOffset,\n highlight,\n isSingleEmoji: Boolean(singleEmoji),\n animatedEmoji: singleEmoji ? selectAnimatedEmoji(global, singleEmoji) : undefined,\n animatedEmojiEffect: singleEmoji && isUserId(chatId) ? selectAnimatedEmojiEffect(global, singleEmoji) : undefined,\n animatedEmojiSoundId: singleEmoji ? selectAnimatedEmojiSound(global, singleEmoji) : undefined,\n localSticker,\n localEffect: localSticker && isUserId(chatId) ? selectLocalAnimatedEmojiEffect(localSticker) : undefined,\n isInSelectMode: selectIsInSelectMode(global),\n isSelected,\n isGroupSelected: (\n Boolean(message.groupedId)\n && !message.isInAlbum\n && 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 availableReactions: global.availableReactions,\n defaultReaction: isMessageLocal(message) ? undefined : selectDefaultReaction(global, chatId),\n activeReaction: reactionMessage && global.activeReactions[reactionMessage.id],\n activeEmojiInteractions: global.activeEmojiInteractions,\n ...(isOutgoing && { outgoingStatus: selectOutgoingStatus(global, message, messageListType === 'scheduled') }),\n ...(typeof uploadProgress === 'number' && { uploadProgress }),\n ...(isFocused && { focusDirection, noFocusHighlight, isResizingContainer }),\n };\n },\n)(Message));\n","import React, { useCallback } from '../../../../lib/teact/teact';\nimport { getActions } from '../../../../global';\n\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 openChat, showNotification, focusMessage, openMediaViewer, openAudioPlayer,\n markMessagesRead, cancelSendingMessage, sendPollVote, openForwardMenu, focusMessageInComments,\n } = getActions();\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 openChat({ id: avatarPeer.id });\n }, [avatarPeer, 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 {\n openChat({ id: senderPeer.id });\n }\n }, [\n asForwarded, focusMessage, forwardInfo, lang, openChat, senderPeer, showNotification,\n ]);\n\n const handleViaBotClick = useCallback(() => {\n if (!botSender) {\n return;\n }\n\n openChat({ id: botSender.id });\n }, [botSender, openChat]);\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 { getActions, withGlobal } from '../../../global';\n\nimport { ApiChat, ApiSponsoredMessage, ApiUser } from '../../../api/types';\n\nimport { renderTextWithEntities } from '../../common/helpers/renderTextWithEntities';\nimport { selectChat, selectSponsoredMessage, selectUser } from '../../../global/selectors';\nimport { getChatTitle, getUserFullName } from '../../../global/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 } = getActions();\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 {\n getMessageHtmlId, getMessageOriginalId, isActionMessage, isOwnMessage,\n} from '../../global/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 { getActions } from '../../global';\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 areReactionsInMeta: 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 areReactionsInMeta,\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 } = getActions();\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 === getMessageHtmlId(message.previousLocalId)) {\n anchorIdRef.current = getMessageHtmlId(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 { getActions } from '../../../global';\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 } = getActions();\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 if (!containerRef.current) {\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 { getActions, withGlobal } from '../../global';\n\nimport { ApiSticker, ApiUpdateConnectionStateType } from '../../api/types';\n\nimport { selectChat } from '../../global/selectors';\nimport { useIntersectionObserver } from '../../hooks/useIntersectionObserver';\nimport useLang from '../../hooks/useLang';\nimport { getUserIdDividend } from '../../global/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 } = getActions();\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 { getActions, getGlobal, withGlobal } from '../../global';\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 '../../global/selectors';\nimport {\n isChatChannel,\n isUserId,\n isChatWithRepliesBot,\n isChatGroup,\n} from '../../global/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';\nimport useInterval from '../../hooks/useInterval';\nimport useNativeCopySelectedMessages from '../../hooks/useNativeCopySelectedMessages';\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 MESSAGE_REACTIONS_POLLING_INTERVAL = 15 * 1000;\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 {\n loadViewportMessages, setScrollOffset, loadSponsoredMessages, loadMessageReactions, copyMessagesByIds,\n } = getActions();\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 useNativeCopySelectedMessages(copyMessagesByIds);\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 useInterval(() => {\n if (!messageIds || !messagesById) {\n return;\n }\n const ids = messageIds.filter((l) => messagesById[l]?.reactions);\n\n if (!ids.length) return;\n\n loadMessageReactions({ chatId, ids });\n }, MESSAGE_REACTIONS_POLLING_INTERVAL);\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 containerRef.current!.dataset.normalHeight = String(containerRef.current!.offsetHeight);\n }, [windowHeight, 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 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] as const);\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 { useEffect } from '../lib/teact/teact';\nimport { IS_MAC_OS } from '../util/environment';\nimport getKeyFromEvent from '../util/getKeyFromEvent';\nimport getMessageIdsForSelectedText from '../util/getMessageIdsForSelectedText';\n\nconst useNativeCopySelectedMessages = (copyMessagesByIds: ({ messageIds }: { messageIds?: number[] }) => void) => {\n useEffect(() => {\n function handleCopy(e: KeyboardEvent) {\n if (((IS_MAC_OS && e.metaKey) || (!IS_MAC_OS && e.ctrlKey)) && getKeyFromEvent(e) === 'c') {\n const messageIds = getMessageIdsForSelectedText();\n\n if (messageIds && messageIds.length > 0) {\n e.preventDefault();\n copyMessagesByIds({ messageIds });\n }\n }\n }\n\n document.addEventListener('keydown', handleCopy, false);\n\n return () => {\n document.removeEventListener('keydown', handleCopy, false);\n };\n }, [copyMessagesByIds]);\n};\n\nexport default useNativeCopySelectedMessages;\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, true);\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 { getActions, withGlobal } from '../../global';\n\nimport { MessageListType } from '../../global/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\n\nimport { selectChat, selectCurrentMessageList } from '../../global/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 } = getActions();\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","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","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 { IOpusRecorder } from 'opus-recorder';\n\nexport type Result = { blob: Blob; duration: number; waveform: number[] };\n\nconst encoderPath = new URL('opus-recorder/dist/encoderWorker.min', import.meta.url).href;\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 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","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';\nimport getFilesFromDataTransferItems from '../helpers/getFilesFromDataTransferItems';\n\nconst CLIPBOARD_ACCEPTED_TYPES = ['image/png', 'image/jpeg', 'image/gif'];\nconst MAX_MESSAGE_LENGTH = 4096;\n\nconst useClipboardPaste = (\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 pastedText = e.clipboardData.getData('text').substring(0, MAX_MESSAGE_LENGTH);\n const { items } = e.clipboardData;\n let files: File[] = [];\n\n e.preventDefault();\n if (items.length > 0) {\n files = await getFilesFromDataTransferItems(items);\n }\n\n if (files.length === 0 && !pastedText) {\n return;\n }\n\n if (files.length > 0 && !editedMessage) {\n const newAttachments = await Promise.all(files.map((file) => {\n return buildAttachment(file.name, file, files.length === 1 && CLIPBOARD_ACCEPTED_TYPES.includes(file.type));\n }));\n setAttachments((attachments) => attachments.concat(newAttachments));\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\nexport default useClipboardPaste;\n","import { useCallback, useEffect, useMemo } from '../../../../lib/teact/teact';\nimport { getActions } from '../../../../global';\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 useBackgroundMode from '../../../../hooks/useBackgroundMode';\nimport useBeforeUnload from '../../../../hooks/useBeforeUnload';\nimport { IS_TOUCH_ENV } from '../../../../util/environment';\nimport { getTextWithEntitiesAsHtml } from '../../../common/helpers/renderTextWithEntities';\n\n// Used to avoid running debounced callbacks when chat changes.\nlet currentChatId: string | undefined;\nlet currentThreadId: number | undefined;\n\nconst useDraft = (\n draft: ApiFormattedText | undefined,\n chatId: string,\n threadId: number,\n htmlRef: { current: string },\n setHtml: (html: string) => void,\n editedMessage: ApiMessage | undefined,\n) => {\n const { saveDraft, clearDraft } = getActions();\n\n const updateDraft = useCallback((draftChatId: string, draftThreadId: number) => {\n const currentHtml = htmlRef.current;\n if (editedMessage) return;\n if (currentHtml.length) {\n saveDraft({ chatId: draftChatId, threadId: draftThreadId, draft: parseMessageInput(currentHtml!) });\n } else if (currentHtml !== undefined) {\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 (editedMessage || !draft) {\n return;\n }\n\n setHtml(getTextWithEntitiesAsHtml(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, editedMessage]);\n\n const html = htmlRef.current;\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\nexport default useDraft;\n","import { useState } from '../lib/teact/teact';\n\nimport useDebounce from './useDebounce';\nimport useOnChange from './useOnChange';\nimport useHeavyAnimationCheck from './useHeavyAnimationCheck';\nimport useFlag from './useFlag';\n\nexport default function useDebouncedMemo(\n resolverFn: () => R, ms: number, dependencies: D,\n): R | undefined {\n const runDebounced = useDebounce(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 runDebounced(() => {\n setValue(resolverFn());\n });\n }, [...dependencies, isFrozen]);\n\n return value;\n}\n","import { useCallback, useEffect } from '../../../../lib/teact/teact';\nimport { getActions } from '../../../../global';\nimport { InlineBotSettings } from '../../../../types';\nimport useFlag from '../../../../hooks/useFlag';\nimport usePrevious from '../../../../hooks/usePrevious';\nimport useDebouncedMemo from '../../../../hooks/useDebouncedMemo';\n\nconst DEBOUNCE_MS = 300;\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;\nconst MEMO_NO_RESULT = {\n username: '',\n query: '',\n canShowHelp: false,\n usernameLowered: '',\n};\n\nconst tempEl = document.createElement('div');\n\nexport default function useInlineBotTooltip(\n isAllowed: boolean,\n chatId: string,\n html: string,\n inlineBots?: Record,\n) {\n const { queryInlineBot, resetInlineBot } = getActions();\n\n const [isOpen, markIsOpen, unmarkIsOpen] = useFlag();\n const {\n username, query, canShowHelp, usernameLowered,\n } = useDebouncedMemo(() => parseBotQuery(html), DEBOUNCE_MS, [html]) || {};\n const prevQuery = usePrevious(query);\n const prevUsername = usePrevious(username);\n const inlineBotData = usernameLowered ? inlineBots?.[usernameLowered] : undefined;\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 id: botId,\n isGallery,\n switchPm,\n results,\n closeTooltip: unmarkIsOpen,\n help: canShowHelp && help ? `@${username} ${help}` : undefined,\n loadMore,\n };\n}\n\nfunction parseBotQuery(html: string) {\n const text = getPlainText(html);\n const result = text.match(INLINE_BOT_QUERY_REGEXP);\n if (!result) {\n return MEMO_NO_RESULT;\n }\n\n return {\n username: result[1],\n query: result[2],\n canShowHelp: result[2] === '' && !text.match(HAS_NEW_LINE),\n usernameLowered: result[1].toLowerCase(),\n };\n}\n\nfunction getPlainText(html: string) {\n tempEl.innerHTML = html.replace(/
/g, '\\n');\n\n return tempEl.innerText;\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 setFilteredBotCommands(undefined);\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 setFilteredBotCommands(undefined);\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, {\n FC, memo, useCallback, useEffect,\n} from '../../../lib/teact/teact';\n\nimport { CONTENT_TYPES_WITH_PREVIEW } from '../../../config';\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { openSystemFilesDialog } from '../../../util/systemFilesDialog';\nimport useMouseInside from '../../../hooks/useMouseInside';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\n\nimport ResponsiveHoverButton from '../../ui/ResponsiveHoverButton';\nimport Menu from '../../ui/Menu';\nimport MenuItem from '../../ui/MenuItem';\n\nimport './AttachMenu.scss';\n\nexport type OwnProps = {\n isButtonVisible: boolean;\n canAttachMedia: boolean;\n canAttachPolls: boolean;\n onFileSelect: (files: File[], isQuick: boolean) => void;\n onPollCreate: () => void;\n};\n\nconst AttachMenu: FC = ({\n isButtonVisible, canAttachMedia, canAttachPolls, onFileSelect, onPollCreate,\n}) => {\n const [isAttachMenuOpen, openAttachMenu, closeAttachMenu] = useFlag();\n const [handleMouseEnter, handleMouseLeave, markMouseInside] = useMouseInside(isAttachMenuOpen, closeAttachMenu);\n\n useEffect(() => {\n if (isAttachMenuOpen) {\n markMouseInside();\n }\n }, [isAttachMenuOpen, markMouseInside]);\n\n const handleFileSelect = useCallback((e: Event, isQuick: boolean) => {\n const { files } = e.target as HTMLInputElement;\n\n if (files && files.length > 0) {\n onFileSelect(Array.from(files), isQuick);\n }\n }, [onFileSelect]);\n\n const handleQuickSelect = useCallback(() => {\n openSystemFilesDialog(\n Array.from(CONTENT_TYPES_WITH_PREVIEW).join(','),\n (e) => handleFileSelect(e, true),\n );\n }, [handleFileSelect]);\n\n const handleDocumentSelect = useCallback(() => {\n openSystemFilesDialog('*', (e) => handleFileSelect(e, false));\n }, [handleFileSelect]);\n\n const lang = useLang();\n\n if (!isButtonVisible) {\n return undefined;\n }\n\n return (\n
\n \n \n \n \n {/*\n ** Using ternary operator here causes some attributes from first clause\n ** transferring to the fragment content in the second clause\n */}\n {!canAttachMedia && (\n Posting media content is not allowed in this group.\n )}\n {canAttachMedia && (\n <>\n \n {lang('AttachmentMenu.PhotoOrVideo')}\n \n {lang('AttachDocument')}\n \n )}\n {canAttachPolls && (\n {lang('Poll')}\n )}\n \n
\n );\n};\n\nexport default memo(AttachMenu);\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 './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 memo(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 { getActions, withGlobal } from '../../../global';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { selectChatMessage, selectCurrentMessageList } from '../../../global/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 } = getActions();\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?.keyboardButtons]);\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 { getActions, withGlobal } from '../../../global';\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 '../../../global/selectors';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport buildClassName from '../../../util/buildClassName';\nimport { isUserId } from '../../../global/helpers';\n\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport useShowTransition from '../../../hooks/useShowTransition';\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\ntype OwnProps = {\n onClear?: () => void;\n};\n\nconst FORWARD_RENDERING_DELAY = 300;\n\nconst ComposerEmbeddedMessage: FC = ({\n replyingToId,\n editingId,\n message,\n sender,\n shouldAnimate,\n forwardedMessagesCount,\n onClear,\n}) => {\n const {\n setReplyingToId,\n setEditingId,\n focusMessage,\n exitForwardMode,\n } = getActions();\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 onClear?.();\n }, [replyingToId, editingId, forwardedMessagesCount, onClear, 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, { FC, memo, useEffect } from '../../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../../global';\n\nimport { ApiMessage, ApiMessageEntityTypes, ApiWebPage } from '../../../api/types';\nimport { ISettings } from '../../../types';\n\nimport { RE_LINK_TEMPLATE } from '../../../config';\nimport { selectNoWebPage, selectTheme } from '../../../global/selectors';\nimport parseMessageInput from '../../../util/parseMessageInput';\nimport useOnChange from '../../../hooks/useOnChange';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useCurrentOrPrev from '../../../hooks/useCurrentOrPrev';\nimport useDebouncedMemo from '../../../hooks/useDebouncedMemo';\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 DEBOUNCE_MS = 300;\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 } = getActions();\n\n const link = useDebouncedMemo(() => {\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 }, DEBOUNCE_MS, [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 './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 { getActions, getGlobal, withGlobal } from '../../../global';\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, SEND_MESSAGE_ACTION_INTERVAL,\n} from '../../../config';\nimport { IS_VOICE_RECORDING_SUPPORTED, IS_SINGLE_COLUMN_LAYOUT, IS_IOS } from '../../../util/environment';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport {\n selectChat,\n selectIsRightColumnShown,\n selectIsInSelectMode,\n selectNewestMessageWithBotKeyboardButtons,\n selectDraft,\n selectScheduledIds,\n selectEditingMessage,\n selectIsChatWithSelf,\n selectChatBot,\n selectChatMessage,\n selectUser,\n selectCanScheduleUntilOnline,\n selectEditingScheduledDraft,\n selectEditingDraft,\n} from '../../../global/selectors';\nimport {\n getAllowedAttachmentOptions,\n getChatSlowModeOptions,\n isChatAdmin,\n isChatSuperGroup,\n isChatChannel,\n} from '../../../global/helpers';\nimport { formatMediaDuration, formatVoiceRecordDuration } 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 { useStateRef } from '../../../hooks/useStateRef';\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';\nimport useSchedule from '../../../hooks/useSchedule';\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';\nimport Avatar from '../../common/Avatar';\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 SendAsMenu from './SendAsMenu.async';\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 isChannel?: 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 recentEmojis: string[];\n lastSyncTime?: number;\n contentToBeScheduled?: GlobalState['messages']['contentToBeScheduled'];\n shouldSuggestStickers?: boolean;\n baseEmojiKeywords?: Record;\n emojiKeywords?: Record;\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 editingDraft?: ApiFormattedText;\n }\n & Pick;\n\nenum MainButtonState {\n Send = 'send',\n Record = 'record',\n Edit = 'edit',\n Schedule = 'schedule',\n}\n\ntype ScheduledMessageArgs = GlobalState['messages']['contentToBeScheduled'] | {\n id: string; queryId: string; isSilent?: boolean;\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 isChannel,\n isRightColumnShown,\n isSelectModeActive,\n isForwarding,\n isPollModalOpen,\n botKeyboardMessageId,\n botKeyboardPlaceholder,\n withScheduledButton,\n stickersForEmoji,\n groupChatMembers,\n topInlineBotIds,\n currentUserId,\n lastSyncTime,\n contentToBeScheduled,\n shouldSuggestStickers,\n baseEmojiKeywords,\n emojiKeywords,\n recentEmojis,\n inlineBots,\n isInlineBotLoading,\n botCommands,\n chatBotCommands,\n sendAsUser,\n sendAsChat,\n sendAsId,\n editingDraft,\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 loadFullChat,\n } = getActions();\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 htmlRef = useStateRef(html);\n const lastMessageSendTimeSeconds = useRef();\n const prevDropAreaState = usePrevious(dropAreaState);\n const { width: windowWidth } = windowSize.get();\n const sendAsIds = chat?.sendAsIds;\n const canShowSendAs = sendAsIds && (sendAsIds.length > 1 || !sendAsIds.includes(currentUserId!));\n // Prevent Symbol Menu from closing when calendar is open\n const [isSymbolMenuForced, forceShowSymbolMenu, cancelForceShowSymbolMenu] = useFlag();\n const sendMessageAction = useSendMessageAction(chatId, threadId);\n\n const handleScheduleCancel = useCallback(() => {\n cancelForceShowSymbolMenu();\n }, [cancelForceShowSymbolMenu]);\n const [requestCalendar, calendar] = useSchedule(canScheduleUntilOnline, handleScheduleCancel);\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 useEffect(() => {\n if (chatId && chat && lastSyncTime && !chat.fullInfo && isReady && isChatSuperGroup(chat)) {\n loadFullChat({ chatId });\n }\n }, [chat, chatId, isReady, lastSyncTime, loadFullChat]);\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 const [attachments, setAttachments] = useState([]);\n\n const [isBotKeyboardOpen, openBotKeyboard, closeBotKeyboard] = useFlag();\n const [isBotCommandMenuOpen, openBotCommandMenu, closeBotCommandMenu] = 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 ? MainButtonState.Edit\n : (!IS_VOICE_RECORDING_SUPPORTED || activeVoiceRecording || (html && !attachments.length) || isForwarding)\n ? (shouldSchedule ? MainButtonState.Schedule : MainButtonState.Send)\n : MainButtonState.Record;\n const canShowCustomSendMenu = !shouldSchedule;\n\n const {\n isMentionTooltipOpen, closeMentionTooltip, insertMention, mentionFilteredUsers,\n } = useMentionTooltip(\n !attachments.length,\n htmlRef,\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 {\n canSendStickers, canSendGifs, canAttachMedia, canAttachPolls, canAttachEmbedLinks,\n } = useMemo(() => getAllowedAttachmentOptions(chat, isChatWithBot), [chat, isChatWithBot]);\n\n const isAdmin = chat && isChatAdmin(chat);\n const slowMode = getChatSlowModeOptions(chat);\n\n const { isStickerTooltipOpen, closeStickerTooltip } = useStickerTooltip(\n Boolean(shouldSuggestStickers && canSendStickers && !attachments.length),\n html,\n stickersForEmoji,\n !isReady,\n );\n const {\n isEmojiTooltipOpen, closeEmojiTooltip, filteredEmojis, insertEmoji,\n } = useEmojiTooltip(\n Boolean(shouldSuggestStickers && canSendStickers && !attachments.length),\n htmlRef,\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 }, [htmlRef]);\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 }, [htmlRef]);\n\n const resetComposer = useCallback((shouldPreserveInput = false) => {\n if (!shouldPreserveInput) {\n setHtml('');\n }\n setAttachments(MEMO_EMPTY_ARRAY);\n closeStickerTooltip();\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, 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, handleEditCancel] = useEditing(\n htmlRef,\n setHtml,\n editingMessage,\n resetComposer,\n openDeleteModal,\n chatId,\n threadId,\n messageListType,\n draft,\n editingDraft,\n );\n useDraft(draft, chatId, threadId, htmlRef, setHtml, editingMessage);\n useClipboardPaste(insertTextAndUpdateCursor, setAttachments, editingMessage);\n\n const handleEmbeddedClear = useCallback(() => {\n if (editingMessage) {\n handleEditCancel();\n }\n }, [editingMessage, handleEditCancel]);\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(MEMO_EMPTY_ARRAY);\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 // No need to subscribe on updates in `mapStateToProps`\n const { serverTimeOffset } = getGlobal();\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,\n resetComposer, stopRecordingVoice, showDialog, slowMode, isAdmin, sendMessage, forwardMessages, lang, htmlRef,\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 handleMessageSchedule = useCallback((\n args: ScheduledMessageArgs, scheduledAt: number,\n ) => {\n if (args && 'queryId' in args) {\n const { id, queryId, isSilent } = args;\n sendInlineBotResult({\n id,\n queryId,\n scheduledAt,\n isSilent,\n });\n return;\n }\n\n const { isSilent, ...restArgs } = args || {};\n\n if (!args || Object.keys(restArgs).length === 0) {\n void handleSend(Boolean(isSilent), scheduledAt);\n } else {\n sendMessage({\n ...args,\n scheduledAt,\n });\n }\n }, [handleSend, sendInlineBotResult, sendMessage]);\n\n useEffect(() => {\n if (contentToBeScheduled) {\n requestCalendar((scheduledAt) => {\n handleMessageSchedule(contentToBeScheduled, scheduledAt);\n });\n }\n }, [contentToBeScheduled, handleMessageSchedule, requestCalendar]);\n\n const handleStickerSelect = useCallback((\n sticker: ApiSticker, isSilent?: boolean, isScheduleRequested?: boolean, shouldPreserveInput = false,\n ) => {\n sticker = {\n ...sticker,\n isPreloadedGlobally: true,\n };\n\n if (shouldSchedule || isScheduleRequested) {\n forceShowSymbolMenu();\n requestCalendar((scheduledAt) => {\n cancelForceShowSymbolMenu();\n handleMessageSchedule({ sticker, isSilent }, scheduledAt);\n requestAnimationFrame(() => {\n resetComposer(shouldPreserveInput);\n });\n });\n } else {\n sendMessage({ sticker, isSilent });\n requestAnimationFrame(() => {\n resetComposer(shouldPreserveInput);\n });\n }\n }, [\n shouldSchedule, forceShowSymbolMenu, requestCalendar, cancelForceShowSymbolMenu, handleMessageSchedule,\n resetComposer, sendMessage,\n ]);\n\n const handleGifSelect = useCallback((gif: ApiVideo, isSilent?: boolean, isScheduleRequested?: boolean) => {\n if (shouldSchedule || isScheduleRequested) {\n forceShowSymbolMenu();\n requestCalendar((scheduledAt) => {\n cancelForceShowSymbolMenu();\n handleMessageSchedule({ gif, isSilent }, scheduledAt);\n requestAnimationFrame(() => {\n resetComposer(true);\n });\n });\n } else {\n sendMessage({ gif, isSilent });\n requestAnimationFrame(() => {\n resetComposer(true);\n });\n }\n }, [\n shouldSchedule, forceShowSymbolMenu, requestCalendar, cancelForceShowSymbolMenu, handleMessageSchedule,\n resetComposer, sendMessage,\n ]);\n\n const handleInlineBotSelect = useCallback((\n inlineResult: ApiBotInlineResult | ApiBotInlineMediaResult, isSilent?: boolean, isScheduleRequested?: boolean,\n ) => {\n if (connectionState !== 'connectionStateReady') {\n return;\n }\n\n if (shouldSchedule || isScheduleRequested) {\n requestCalendar((scheduledAt) => {\n handleMessageSchedule({\n id: inlineResult.id,\n queryId: inlineResult.queryId,\n isSilent,\n }, scheduledAt);\n });\n } else {\n sendInlineBotResult({\n id: inlineResult.id,\n queryId: inlineResult.queryId,\n isSilent,\n });\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 }, [\n chatId, clearDraft, connectionState, handleMessageSchedule, requestCalendar, resetComposer, sendInlineBotResult,\n shouldSchedule,\n ]);\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 requestCalendar((scheduledAt) => {\n handleMessageSchedule({ poll }, scheduledAt);\n });\n closePollModal();\n } else {\n sendMessage({ poll });\n closePollModal();\n }\n }, [closePollModal, handleMessageSchedule, requestCalendar, sendMessage, shouldSchedule]);\n\n const handleSendSilent = useCallback(() => {\n if (shouldSchedule) {\n requestCalendar((scheduledAt) => {\n handleMessageSchedule({ isSilent: true }, scheduledAt);\n });\n } else {\n void handleSend(true);\n }\n }, [handleMessageSchedule, handleSend, requestCalendar, shouldSchedule]);\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 handleSend();\n break;\n case MainButtonState.Record:\n void startRecordingVoice();\n break;\n case MainButtonState.Edit:\n handleEditComplete();\n break;\n case MainButtonState.Schedule:\n if (activeVoiceRecording) {\n pauseRecordingVoice();\n }\n requestCalendar((scheduledAt) => {\n handleMessageSchedule({}, scheduledAt);\n });\n break;\n default:\n break;\n }\n }, [\n mainButtonState, handleSend, startRecordingVoice, handleEditComplete, activeVoiceRecording, requestCalendar,\n pauseRecordingVoice, handleMessageSchedule,\n ]);\n\n const areVoiceMessagesNotAllowed = mainButtonState === MainButtonState.Record && !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 handleSendScheduled = useCallback(() => {\n requestCalendar((scheduledAt) => {\n handleMessageSchedule({}, scheduledAt);\n });\n }, [handleMessageSchedule, requestCalendar]);\n\n const onSend = mainButtonState === MainButtonState.Edit\n ? handleEditComplete\n : mainButtonState === MainButtonState.Schedule ? handleSendScheduled\n : handleSend;\n\n return (\n
\n {canAttachMedia && isReady && (\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 {canShowSendAs && (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 && 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 \n {canShowCustomSendMenu && (\n \n )}\n {calendar}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const chat = selectChat(global, chatId);\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 { currentUserId } = global;\n const defaultSendAsId = chat?.fullInfo ? chat?.fullInfo?.sendAsId || currentUserId : undefined;\n const sendAsId = chat?.sendAsIds && defaultSendAsId && chat.sendAsIds.includes(defaultSendAsId)\n ? defaultSendAsId\n : (chat?.adminRights?.anonymous ? chat?.id : undefined);\n const sendAsUser = sendAsId ? selectUser(global, sendAsId) : undefined;\n const sendAsChat = !sendAsUser && sendAsId ? selectChat(global, sendAsId) : undefined;\n\n const editingDraft = messageListType === 'scheduled'\n ? selectEditingScheduledDraft(global, chatId)\n : selectEditingDraft(global, chatId, threadId);\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: selectCanScheduleUntilOnline(global, chatId),\n isChannel: chat ? isChatChannel(chat) : undefined,\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 lastSyncTime: global.lastSyncTime,\n contentToBeScheduled: global.messages.contentToBeScheduled,\n shouldSuggestStickers,\n recentEmojis: global.recentEmojis,\n baseEmojiKeywords: baseEmojiKeywords?.keywords,\n emojiKeywords: emojiKeywords?.keywords,\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 editingDraft,\n };\n },\n)(Composer));\n","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\nconst useVoiceRecording = () => {\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\nexport default useVoiceRecording;\n","import { useEffect, useMemo } from '../../../../lib/teact/teact';\nimport { getActions } from '../../../../global';\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 } = getActions();\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 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 { getActions } from '../../../../global';\n\nimport { ApiFormattedText, ApiMessage } from '../../../../api/types';\nimport { MessageListType } from '../../../../global/types';\n\nimport useEffectWithPrevDeps from '../../../../hooks/useEffectWithPrevDeps';\nimport { EDITABLE_INPUT_ID } from '../../../../config';\nimport parseMessageInput from '../../../../util/parseMessageInput';\nimport focusEditableElement from '../../../../util/focusEditableElement';\nimport { hasMessageMedia } from '../../../../global/helpers';\nimport { getTextWithEntitiesAsHtml } from '../../../common/helpers/renderTextWithEntities';\nimport { fastRaf } from '../../../../util/schedulers';\nimport useBackgroundMode from '../../../../hooks/useBackgroundMode';\nimport useBeforeUnload from '../../../../hooks/useBeforeUnload';\n\nconst useEditing = (\n htmlRef: { current: string },\n setHtml: (html: string) => void,\n editedMessage: ApiMessage | undefined,\n resetComposer: (shouldPreserveInput?: boolean) => void,\n openDeleteModal: () => void,\n chatId: string,\n threadId: number,\n type: MessageListType,\n draft?: ApiFormattedText,\n editingDraft?: ApiFormattedText,\n) => {\n const { editMessage, setEditingDraft } = getActions();\n\n useEffectWithPrevDeps(([prevEditedMessage]) => {\n if (!editedMessage) {\n return;\n }\n if (prevEditedMessage?.id === editedMessage.id) {\n return;\n }\n\n const html = getTextWithEntitiesAsHtml(editingDraft?.text.length ? editingDraft : editedMessage.content.text);\n setHtml(html);\n // `fastRaf` would execute syncronously in this case\n requestAnimationFrame(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n focusEditableElement(messageInput, true);\n });\n }, [editedMessage, setHtml] as const);\n\n useEffect(() => {\n if (!editedMessage) return undefined;\n return () => {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const edited = parseMessageInput(htmlRef.current!);\n const update = edited.text.length ? edited : undefined;\n setEditingDraft({\n chatId, threadId, type, text: update,\n });\n };\n }, [chatId, editedMessage, htmlRef, setEditingDraft, threadId, type]);\n\n const restoreNewDraftAfterEditing = useCallback(() => {\n if (!draft) return;\n // Run 1 frame after editing draft reset\n fastRaf(() => {\n setHtml(getTextWithEntitiesAsHtml(draft));\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n requestAnimationFrame(() => {\n focusEditableElement(messageInput, true);\n });\n });\n }, [draft, setHtml]);\n\n const handleEditCancel = useCallback(() => {\n resetComposer();\n restoreNewDraftAfterEditing();\n }, [resetComposer, restoreNewDraftAfterEditing]);\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 restoreNewDraftAfterEditing();\n }, [editMessage, editedMessage, htmlRef, openDeleteModal, resetComposer, restoreNewDraftAfterEditing]);\n\n const handleBlur = useCallback(() => {\n if (!editedMessage) return;\n const edited = parseMessageInput(htmlRef.current!);\n const update = edited.text.length ? edited : undefined;\n setEditingDraft({\n chatId, threadId, type, text: update,\n });\n }, [chatId, editedMessage, htmlRef, setEditingDraft, threadId, type]);\n\n useBackgroundMode(handleBlur);\n useBeforeUnload(handleBlur);\n\n return [handleEditComplete, handleEditCancel];\n};\n\nexport default useEditing;\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, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './EmojiInteractionAnimation';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst EmojiInteractionAnimationAsync: FC = (props) => {\n const { activeEmojiInteraction } = props;\n const EmojiInteractionAnimation = useModuleLoader(\n Bundles.Extra, 'EmojiInteractionAnimation', !activeEmojiInteraction,\n );\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return EmojiInteractionAnimation ? : undefined;\n};\n\nexport default memo(EmojiInteractionAnimationAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './ReactorListModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst ReactorListModalAsync: FC = (props) => {\n const { isOpen } = props;\n const ReactorListModal = useModuleLoader(Bundles.Extra, 'ReactorListModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ReactorListModal ? : undefined;\n};\n\nexport default memo(ReactorListModalAsync);\n","import React, {\n FC, useEffect, useState, memo, useMemo, useCallback,\n} from '../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../global';\n\nimport { ApiChatBannedRights, MAIN_THREAD_ID } from '../../api/types';\nimport {\n MessageListType,\n MessageList as GlobalMessageList,\n ActiveEmojiInteraction,\n} 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 '../../global/selectors';\nimport {\n getCanPostInChat, getMessageSendingRestrictionReason, isChatChannel, isChatSuperGroup, isUserId,\n} from '../../global/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';\nimport EmojiInteractionAnimation from './EmojiInteractionAnimation.async';\nimport ReactorListModal from './ReactorListModal.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 isReactorListModalOpen: boolean;\n animationLevel?: number;\n shouldSkipHistoryAnimations?: boolean;\n currentTransitionKey: number;\n messageLists?: GlobalMessageList[];\n isChannel?: boolean;\n areChatSettingsLoaded?: boolean;\n canSubscribe?: boolean;\n canStartBot?: boolean;\n canRestartBot?: boolean;\n activeEmojiInteractions?: ActiveEmojiInteraction[];\n lastSyncTime?: number;\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 isReactorListModalOpen,\n animationLevel,\n shouldSkipHistoryAnimations,\n currentTransitionKey,\n isChannel,\n areChatSettingsLoaded,\n canSubscribe,\n canStartBot,\n canRestartBot,\n activeEmojiInteractions,\n lastSyncTime,\n}) => {\n const {\n openChat,\n unpinAllMessages,\n loadUser,\n loadChatSettings,\n closeLocalTextSearch,\n exitMessageSelectMode,\n closePaymentModal,\n clearReceipt,\n joinChannel,\n sendBotCommand,\n restartBot,\n } = getActions();\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 !shouldSkipHistoryAnimations && animationLevel !== ANIMATION_LEVEL_MIN,\n currentTransitionKey,\n prevTransitionKey,\n 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 useEffect(() => {\n if (!areChatSettingsLoaded && lastSyncTime) {\n loadChatSettings({ chatId });\n }\n }, [chatId, isPrivate, areChatSettingsLoaded, lastSyncTime, loadChatSettings]);\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 && items.length > 0 && 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,\n undefined,\n undefined,\n undefined,\n messageLists?.map(createMessageHash) || [],\n );\n\n useHistoryBack(isMobileSearchActive, closeLocalTextSearch);\n useHistoryBack(isSelectModeActive, exitMessageSelectMode);\n\n const isMessagingDisabled = Boolean(\n !isPinnedMessageList && !renderingCanPost && !renderingCanRestartBot && !renderingCanStartBot\n && !renderingCanSubscribe && messageSendingRestrictionReason,\n );\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 {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 {IS_SINGLE_COLUMN_LAYOUT && }\n \n )}\n {chatId && (\n \n )}\n
\n {activeEmojiInteractions?.map((activeEmojiInteraction, i) => (\n \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 {\n isLeftColumnShown, chats: { listIds }, activeEmojiInteractions, lastSyncTime,\n } = 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 isReactorListModalOpen: Boolean(global.reactorModal),\n animationLevel: global.settings.byKey.animationLevel,\n currentTransitionKey: Math.max(0, global.messages.messageLists.length - 1),\n activeEmojiInteractions,\n lastSyncTime,\n };\n\n if (!currentMessageList || !listIds.active) {\n return state;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const isPrivate = isUserId(chatId);\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,\n areChatSettingsLoaded: Boolean(chat?.settings),\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 withAnimations?: boolean,\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 (withAnimations) {\n setIsReady(false);\n } else {\n forceUpdate();\n }\n }\n\n useOnChange(() => {\n if (!withAnimations) {\n setIsReady(true);\n }\n }, [withAnimations]);\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: withAnimations ? handleOpenEnd : undefined,\n handleSlideStop: withAnimations ? handleSlideStop : undefined,\n };\n}\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../global';\n\nimport { ManagementScreens, ProfileState } from '../../types';\nimport { ApiExportedInvite } from '../../api/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 '../../global/selectors';\nimport {\n getCanAddContact, isChatAdmin, isChatChannel, isUserId,\n} from '../../global/helpers';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport useLang from '../../hooks/useLang';\nimport useFlag from '../../hooks/useFlag';\nimport { getDayStartAt } from '../../util/dateFormat';\n\nimport SearchInput from '../ui/SearchInput';\nimport Button from '../ui/Button';\nimport Transition from '../ui/Transition';\nimport ConfirmDialog from '../ui/ConfirmDialog';\n\nimport './RightHeader.scss';\n\ntype OwnProps = {\n chatId?: string;\n isColumnOpen?: boolean;\n isProfile?: boolean;\n isSearch?: boolean;\n isManagement?: boolean;\n isStatistics?: 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 onScreenSelect: (screen: ManagementScreens) => void;\n};\n\ntype StateProps = {\n canAddContact?: boolean;\n canManage?: boolean;\n canViewStatistics?: boolean;\n isChannel?: boolean;\n userId?: string;\n messageSearchQuery?: string;\n stickerSearchQuery?: string;\n gifSearchQuery?: string;\n isEditingInvite?: boolean;\n currentInviteInfo?: ApiExportedInvite;\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 Statistics,\n Management,\n ManageInitial,\n ManageChannelSubscribers,\n ManageChatAdministrators,\n ManageChatPrivacyType,\n ManageDiscussion,\n ManageGroupPermissions,\n ManageGroupRemovedUsers,\n ManageChannelRemovedUsers,\n ManageGroupUserPermissionsCreate,\n ManageGroupUserPermissions,\n ManageGroupRecentActions,\n ManageGroupAdminRights,\n ManageGroupNewAdminRights,\n ManageGroupMembers,\n ManageGroupAddAdmins,\n StickerSearch,\n GifSearch,\n PollResults,\n AddingMembers,\n ManageInvites,\n ManageEditInvite,\n ManageReactions,\n ManageInviteInfo,\n ManageJoinRequests,\n}\n\nconst RightHeader: FC = ({\n chatId,\n isColumnOpen,\n isProfile,\n isSearch,\n isManagement,\n isStatistics,\n isStickerSearch,\n isGifSearch,\n isPollResults,\n isAddingChatMembers,\n profileState,\n managementScreen,\n canAddContact,\n userId,\n canManage,\n isChannel,\n onClose,\n onScreenSelect,\n messageSearchQuery,\n stickerSearchQuery,\n gifSearchQuery,\n shouldSkipAnimation,\n isEditingInvite,\n canViewStatistics,\n currentInviteInfo,\n}) => {\n const {\n setLocalTextSearchQuery,\n setStickerSearchQuery,\n setGifSearchQuery,\n searchTextMessagesLocal,\n toggleManagement,\n openHistoryCalendar,\n openAddContactDialog,\n toggleStatistics,\n setEditingExportedInvite,\n deleteExportedChatInvite,\n } = getActions();\n\n // eslint-disable-next-line no-null/no-null\n const backButtonRef = useRef(null);\n const [isDeleteDialogOpen, openDeleteDialog, closeDeleteDialog] = useFlag();\n\n const handleEditInviteClick = useCallback(() => {\n setEditingExportedInvite({ chatId: chatId!, invite: currentInviteInfo! });\n onScreenSelect(ManagementScreens.EditInvite);\n }, [chatId, currentInviteInfo, onScreenSelect, setEditingExportedInvite]);\n\n const handleDeleteInviteClick = useCallback(() => {\n deleteExportedChatInvite({ chatId: chatId!, link: currentInviteInfo!.link });\n onScreenSelect(ManagementScreens.Invites);\n closeDeleteDialog();\n }, [chatId, closeDeleteDialog, currentInviteInfo, deleteExportedChatInvite, onScreenSelect]);\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 openAddContactDialog({ userId });\n }, [openAddContactDialog, 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.ChannelRemovedUsers ? (\n HeaderContent.ManageChannelRemovedUsers\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.Invites ? (\n HeaderContent.ManageInvites\n ) : managementScreen === ManagementScreens.EditInvite ? (\n HeaderContent.ManageEditInvite\n ) : managementScreen === ManagementScreens.GroupAddAdmins ? (\n HeaderContent.ManageGroupAddAdmins\n ) : managementScreen === ManagementScreens.Reactions ? (\n HeaderContent.ManageReactions\n ) : managementScreen === ManagementScreens.InviteInfo ? (\n HeaderContent.ManageInviteInfo\n ) : managementScreen === ManagementScreens.JoinRequests ? (\n HeaderContent.ManageJoinRequests\n ) : undefined // Never reached\n ) : isStatistics ? (\n HeaderContent.Statistics\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('BlockedUsers')}

;\n case HeaderContent.ManageChannelRemovedUsers:\n return

{lang('ChannelBlockedUsers')}

;\n case HeaderContent.ManageGroupUserPermissionsCreate:\n return

{lang('ChannelAddException')}

;\n case HeaderContent.ManageGroupUserPermissions:\n return

{lang('UserRestrictions')}

;\n case HeaderContent.ManageInvites:\n return

{lang('lng_group_invite_title')}

;\n case HeaderContent.ManageEditInvite:\n return

{isEditingInvite ? lang('EditLink') : lang('NewLink')}

;\n case HeaderContent.ManageInviteInfo:\n return (\n <>\n

{lang('InviteLink')}

\n
\n {currentInviteInfo && !currentInviteInfo.isRevoked && (\n \n \n \n )}\n {currentInviteInfo && currentInviteInfo.isRevoked && (\n <>\n \n \n \n \n \n )}\n
\n \n );\n case HeaderContent.ManageJoinRequests:\n return

{isChannel ? lang('SubscribeRequests') : lang('MemberRequests')}

;\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.Statistics:\n return

{lang('Statistics')}

;\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 case HeaderContent.ManageReactions:\n return

{lang('Reactions')}

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

Profile

\n
\n {canAddContact && (\n \n \n \n )}\n {canManage && (\n \n \n \n )}\n {canViewStatistics && (\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 const isEditingInvite = Boolean(chatId && global.management.byChatId[chatId]?.editingInvite);\n const canViewStatistics = chat?.fullInfo?.canViewStatistics;\n const currentInviteInfo = chatId ? global.management.byChatId[chatId]?.inviteInfo?.invite : undefined;\n\n return {\n canManage,\n canAddContact,\n canViewStatistics,\n isChannel,\n userId: user?.id,\n messageSearchQuery,\n stickerSearchQuery,\n gifSearchQuery,\n isEditingInvite,\n currentInviteInfo,\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 '../../../global/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 );\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 { getActions, withGlobal } from '../../global';\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 '../../global/helpers';\nimport {\n selectChatMessages,\n selectChat,\n selectCurrentMediaSearch,\n selectIsRightColumnShown,\n selectTheme,\n selectActiveDownloadIds,\n selectUser,\n} from '../../global/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';\nimport { useIntersectionObserver } from '../../hooks/useIntersectionObserver';\n\ntype OwnProps = {\n chatId: 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;\nconst INTERSECTION_THROTTLE = 500;\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 focusMessage,\n loadProfilePhotos,\n setNewChatMembersDialogState,\n } = getActions();\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,\n loadMoreMembers,\n loadCommonChats,\n searchMediaMessagesLocal,\n tabType,\n mediaSearchType,\n members,\n commonChatIds,\n usersById,\n userStatusesById,\n chatsById,\n chatMessages,\n foundIds,\n chatId,\n 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 { observe: observeIntersectionForMedia } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE,\n });\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 openChat({ id });\n }, [openChat]);\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 canRenderContent = 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 renderContent() {\n if (!viewportIds || !canRenderContent || !chatMessages) {\n const noSpinner = isFirstTab && !canRenderContent;\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 {renderContent()}\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 }): StateProps => {\n const chat = selectChat(global, chatId);\n const chatMessages = selectChatMessages(global, 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 const activeDownloadIds = selectActiveDownloadIds(global, chatId);\n\n let hasCommonChatsTab;\n let resolvedUserId;\n let user;\n if (isUserId(chatId)) {\n resolvedUserId = chatId;\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\nconst useCacheBuster = () => {\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\nexport default useCacheBuster;\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 } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './Statistics';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst StatisticsAsync: FC = (props) => {\n const Statistics = useModuleLoader(Bundles.Extra, 'Statistics');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Statistics ? : ;\n};\n\nexport default StatisticsAsync;\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 { getActions, getGlobal, withGlobal } from '../../global';\n\nimport {\n ApiChat, ApiChatMember, ApiUpdateConnectionStateType,\n} from '../../api/types';\nimport { NewChatMembersProgress } from '../../types';\n\nimport { unique } from '../../util/iteratees';\nimport { selectChat } from '../../global/selectors';\nimport {\n filterUsersByName, isChatChannel, isUserBot, sortChatIds,\n} from '../../global/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 } = getActions();\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 { getActions, withGlobal } from '../../global';\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 '../../global/selectors';\nimport useLayoutEffectWithPrevDeps from '../../hooks/useLayoutEffectWithPrevDeps';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useHistoryBack from '../../hooks/useHistoryBack';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\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 Statistics from './statistics/Statistics.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 isChatSelected: boolean;\n shouldSkipHistoryAnimations?: boolean;\n nextManagementScreen?: ManagementScreens;\n};\n\nconst CLOSE_ANIMATION_DURATION = 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 isChatSelected,\n shouldSkipHistoryAnimations,\n nextManagementScreen,\n}) => {\n const {\n toggleChatInfo,\n toggleManagement,\n closeLocalTextSearch,\n setStickerSearchQuery,\n setGifSearchQuery,\n closePollResults,\n addChatMembers,\n setNewChatMembersDialogState,\n setEditingExportedInvite,\n toggleStatistics,\n setOpenedInviteInfo,\n requestNextManagementScreen,\n } = getActions();\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;\n const isSearch = contentKey === RightColumnContent.Search;\n const isManagement = contentKey === RightColumnContent.Management;\n const isStatistics = contentKey === RightColumnContent.Statistics;\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.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 case ManagementScreens.Invites:\n case ManagementScreens.Reactions:\n case ManagementScreens.JoinRequests:\n case ManagementScreens.ChannelRemovedUsers:\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 case ManagementScreens.EditInvite:\n case ManagementScreens.InviteInfo:\n setManagementScreen(ManagementScreens.Invites);\n setOpenedInviteInfo({ invite: undefined });\n setEditingExportedInvite({ chatId, invite: undefined });\n break;\n }\n\n break;\n }\n case RightColumnContent.Statistics:\n toggleStatistics();\n break;\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, closePollResults, setNewChatMembersDialogState,\n managementScreen, toggleManagement, closeLocalTextSearch, setStickerSearchQuery, setGifSearchQuery,\n setEditingExportedInvite, chatId, setOpenedInviteInfo, toggleStatistics,\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 }, CLOSE_ANIMATION_DURATION);\n }, [isOpen]);\n\n useEffect(() => {\n if (nextManagementScreen) {\n setManagementScreen(nextManagementScreen);\n requestNextManagementScreen(undefined);\n }\n }, [nextManagementScreen, requestNextManagementScreen]);\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(([prevChatId]) => {\n if (prevChatId !== chatId) {\n setProfileState(ProfileState.Profile);\n setManagementScreen(ManagementScreens.Initial);\n }\n }, [chatId]);\n\n useHistoryBack(isChatSelected && (\n contentKey === RightColumnContent.ChatInfo\n || 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 return (\n \n );\n case RightColumnContent.Search:\n return ;\n case RightColumnContent.Management:\n return (\n \n );\n\n case RightColumnContent.Statistics:\n return ;\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 const nextManagementScreen = chatId ? global.management.byChatId[chatId]?.nextScreen : undefined;\n\n return {\n contentKey: selectRightColumnContentKey(global),\n chatId,\n threadId,\n isChatSelected: Boolean(chatId && areActiveChatsLoaded),\n shouldSkipHistoryAnimations: global.shouldSkipHistoryAnimations,\n nextManagementScreen,\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 { getActions, withGlobal } from '../../global';\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 '../../global/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 } = getActions();\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, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport { OwnProps } from './NewContactModal';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst NewContactModalAsync: FC = (props) => {\n const { isOpen } = props;\n const NewContactModal = useModuleLoader(Bundles.Extra, 'NewContactModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return NewContactModal ? : undefined;\n};\n\nexport default memo(NewContactModalAsync);\n","import React, {\n FC, useEffect, memo, useCallback,\n} from '../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../global';\n\nimport { LangCode } from '../../types';\nimport { ApiMessage, ApiUpdateAuthorizationStateType, ApiUpdateConnectionStateType } from '../../api/types';\n\nimport '../../global/actions/all';\nimport {\n BASE_EMOJI_KEYWORD_LANG, DEBUG, INACTIVE_MARKER, PAGE_TITLE,\n} from '../../config';\nimport {\n selectChatMessage,\n selectIsForwardModalOpen,\n selectIsMediaViewerOpen,\n selectIsRightColumnShown,\n selectIsServiceChatReady,\n} from '../../global/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 { getAllNotificationsCount } from '../../util/folderManager';\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 StickerSetModal from '../common/StickerSetModal.async';\nimport UnreadCount from '../common/UnreadCounter';\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 GroupCall from '../calls/group/GroupCall.async';\nimport ActiveCallHeader from '../calls/ActiveCallHeader.async';\nimport CallFallbackConfirm from '../calls/CallFallbackConfirm.async';\nimport NewContactModal from './NewContactModal.async';\n\nimport './Main.scss';\n\ntype StateProps = {\n connectionState?: ApiUpdateConnectionStateType;\n authState?: ApiUpdateAuthorizationStateType;\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 newContactUserId?: string;\n newContactByPhoneNumber?: boolean;\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 connectionState,\n authState,\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 newContactUserId,\n newContactByPhoneNumber,\n}) => {\n const {\n sync,\n loadAnimatedEmojis,\n loadNotificationSettings,\n loadNotificationExceptions,\n updateIsOnline,\n loadTopInlineBots,\n loadEmojiKeywords,\n loadCountryList,\n loadAvailableReactions,\n loadStickerSets,\n loadAddedStickers,\n loadFavoriteStickers,\n ensureTimeFormat,\n openStickerSetShortName,\n checkVersionNotification,\n loadAppConfig,\n } = getActions();\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 useEffect(() => {\n if (connectionState === 'connectionStateReady' && authState === 'authorizationStateReady') {\n sync();\n }\n }, [connectionState, authState, sync]);\n\n // Initial API calls\n useEffect(() => {\n if (lastSyncTime) {\n updateIsOnline(true);\n loadAppConfig();\n loadAvailableReactions();\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, loadAvailableReactions, loadAppConfig,\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 (lastSyncTime) {\n if (!addedSetIds) {\n loadStickerSets();\n loadFavoriteStickers();\n } else {\n loadAddedStickers();\n }\n }\n }, [lastSyncTime, 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 = getAllNotificationsCount();\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 = getAllNotificationsCount() - 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 );\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 connectionState: global.connectionState,\n authState: global.authState,\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 newContactUserId: global.newContact?.userId,\n newContactByPhoneNumber: global.newContact?.isByPhoneNumber,\n };\n },\n)(Main));\n","import { getActions, getGlobal } from '../global';\n\nimport { DEBUG } from '../config';\n\n// eslint-disable-next-line import/no-cycle\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 getActions().initApi();\n}\n"],"names":["closeLocalTextSearch","global","chatId","threadId","selectCurrentMessageList","updateLocalTextSearch","replaceLocalTextSearchResults","undefined","addActionHandler","actions","payload","query","chatThreadKey","buildChatThreadKey","currentQuery","localTextSearch","byChatThreadKey","MEMO_EMPTY_ARRAY","mediaType","updateLocalMediaSearchType","id","MAIN_THREAD_ID","type","shouldReplaceHistory","currentMessageList","replaceThreadParam","exitMessageSelectMode","isStatisticsShown","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","copyTextForMessages","messageIds","lang","langProvider","chatMessages","selectChatMessages","result","map","filter","message","selectAllowedMessageActions","canCopy","sort","message1","message2","reduce","acc","sender","selectSender","push","getSenderTitle","getMessageSummaryText","copyTextToClipboard","join","scrollOffset","messageId","paramName","text","viewportIds","selectViewportIds","lastOwnEditableMessageId","findLast","Boolean","canEdit","replyingToId","selectReplyingToId","selectIsViewportNewest","chatMessageKeys","Object","keys","newIndex","toString","length","Number","chat","selectChat","lastMessage","threadInfo","selectThreadInfo","lastMessageId","setReplyingToId","focusMessage","origin","volume","playbackRate","isMuted","audioPlayer","selectIsRightColumnShown","pollResults","voters","window","setTimeout","getGlobal","noHighlight","replyStack","selectReplyStack","pop","focusLastMessage","messageListType","groupedId","groupedChatId","replyMessageId","isResizingContainer","ids","selectForwardedMessageIdsByGroupId","shouldSwitchChat","clearTimeout","newGlobal","updateFocusedMessage","updateFocusDirection","FocusDirection","includes","direction","loadViewportMessages","fromChatId","groupedMessageIds","selectMessageIdsByGroupId","isModalShown","closeMediaViewer","selectedMessages","openForwardMenu","byChatId","activeDownloads","canDownload","forEach","downloadMessageMedia","selectCurrentChat","enterMessageSelectMode","childMessageIds","withShift","toggleMessageSelection","shouldShowContextMenuHint","disableContextMenuHint","showNotification","IS_TOUCH_ENV","isPollModalOpen","currentVersion","APP_VERSION","slice","serviceNotifications","find","version","SERVICE_NOTIFICATIONS_USER_ID","date","getServerTime","serverTimeOffset","content","parseMessageInput","versionNotification","isOutgoing","createServiceNotification","serviceChat","maxId","Math","max","fractionalPart","floor","serviceNotification","isUnread","apiUpdate","reactorModal","seenByModal","globalSearch","updateGlobalSearch","globalResults","localResults","resultsByType","fetchingStatus","chats","recentlyFoundChatIds","newRecentIds","unshift","updateGlobalSearchContent","stickers","search","resultIds","gifs","offsetId","results","updateUserSearch","globalUserIds","localUserIds","userId","newContact","isByPhoneNumber","closeNewContactDialog","action","leftColumnWidth","management","isActive","screen","nextScreen","IS_SINGLE_COLUMN_LAYOUT","IS_TABLET_COLUMN_LAYOUT","isLeftColumnShown","messageLists","emoji","recentEmojis","newEmojis","e","sticker","recent","hash","newStickers","s","notification","localId","generateIdFor","newNotifications","notifications","existingNotificationIndex","findIndex","n","splice","data","hasErrorKey","getReadableErrorText","newDialogs","dialogs","existingErrorIndex","err","url","safeLinkModalUrl","selectedAt","historyCalendarSelectedAt","payment","isPaymentModalOpen","clearPayment","closeInvoice","error","avatarOwnerId","profilePhotoIndex","mediaViewer","uploadProgressCallbacks","Map","runDebouncedForMarkRead","debounce","cb","async","isOutlying","isBudgetPreload","addOffset","LoadMoreDirection","round","MESSAGE_LIST_SLICE","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","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","cached","setsById","loadStickers","stickerSetId","pause","recentStickers","loadRecentStickers","favorite","favoriteStickers","loadFavoriteStickers","greeting","featured","featuredStickers","loadFeaturedStickers","stickerSetShortName","stickerSetAccessHash","stickerSet","selectStickerSet","accessHash","packs","updateStickerSet","currentEmoji","forEmoji","rebuildStickersForEmoji","replaceAnimatedEmojis","loadAnimatedEmojis","animatedEmojiEffects","loadAnimatedEmojiEffects","saved","savedGifs","loadSavedGifs","gif","shouldUnsave","newGifs","unfave","unfaveSticker","installedDate","language","currentEmojiKeywords","emojiKeywords","isLoading","fromVersion","keywords","searchStickers","title","searchWords","updateStickersForEmoji","loadStickersForEmoji","openedStickerSetShortName","searchMessagesGlobal","offsetRate","maxDate","minDate","localResult","GLOBAL_SEARCH_SLICE","totalCount","nextOffsetId","nextRate","currentSearchQuery","selectCurrentGlobalSearchQuery","updateGlobalSearchFetchingStatus","addMessages","updateGlobalSearchResults","searchSharedMedia","SHARED_MEDIA_SLICE","newFoundIds","currentSearch","selectCurrentMediaSearch","updateLocalMediaSearchResults","localChats","localUsers","globalChats","globalUsers","chatIds","userIds","searchChats","timestampPlusDay","foundIds","selectCurrentTextSearch","topMessageId","MESSAGE_SEARCH_SLICE","updateLocalTextSearchResults","searchTextMessages","currentType","currentResults","timestamp","getActions","searchMessagesByDate","ManagementProgress","username","updateManagementProgress","updateManagement","isUsernameAvailable","isChatBasicGroup","invite","editingInvite","update","inviteInfo","adminId","isRevoked","admin","revokedInvites","invites","link","expireDate","usageLimit","isRequestNeeded","oldInvite","newInvite","current","managementState","offsetDate","offsetUserId","offsetUser","currentInviteInfo","importers","isRequested","requesters","joinRequests","isApproved","targetChat","importer","recentRequesterIds","requestsPending","settings","releaseStatusTimeout","loadTopMessages","DEBUG","console","log","isSyncing","loadAllChats","preloadTopChatMessages","listType","shouldReplace","onReplace","areMessagesLoaded","draftsByChatId","editingDraft","selectEditingDraft","currentChatId","currentThreadId","currentChat","newCurrentChatId","currentMessageListInfo","originChannelId","currentMessageListInfoOrigin","resultOrigin","byIdOrigin","listedIdsOrigin","threadsById","updateChats","updateUsers","updateThread","audioChatId","audioMessageId","closeAudioPlayer","loadAndReplaceMessages","lastSyncTime","initFolderManager","runDebouncedForFetchFullUser","runThrottledForSearch","replaceInlineBotSettings","inlineBotSettings","inlineBots","byUsername","replaceInlineBotsIsLoading","userStatusesById","replaceUserStatuses","statusesById","topPeers","lastRequestedAt","loadTopUsers","contactList","getCompareString","lastName","firstName","collator","Intl","Collator","sortedUsers","compare","isSelf","loadContactList","isUserBot","commonChats","isFullyLoaded","updateUser","shouldSharePhoneNumber","updateChatMutedState","isContact","phoneNumber","phone","updateContact","deleteContact","profileId","isPrivate","isUserId","photos","userSearch","updateUserSearchFetchingStatus","searchUsers","userOrChat","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","scheduleDate","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","nativeProvider","credentials","publishableKey","selectProviderPublishableKey","k","buildQueryString","cardNumber","expiryMonth","expiryYear","cvv","zip","country","response","fetch","method","headers","Authorization","json","getStripeError","setStripeCardInfo","sendStripeCredentials","publicToken","selectProviderPublicToken","card","number","replace","expiration_month","expiration_year","security_code","DEBUG_PAYMENT_SMART_GLOCAL","Accept","body","JSON","stringify","status","setSmartGlocalCardInfo","token","sendSmartGlocalCredentials","shippingOptionId","saveCredentials","formId","selectPaymentFormId","requestInfoId","selectPaymentRequestId","requestedInfoId","sendPaymentForm","save","selectStripeCredentials","selectSmartGlocalCredentials","MAX_MESSAGES_LIST_WIDTH","SIDE_COLUMN_MAX_WIDTH","MIN_LEFT_COLUMN_WIDTH","subtractXForEmojiInteraction","x","windowWidth","windowSize","width","MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","min","MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN","interactionLocalId","availableReaction","aroundAnimation","mediaLoader","ApiMediaFormat","centerIcon","availableReactions","y","localEffect","startSize","isReversed","activeEmojiInteraction","animatedEffect","INTERACTION_RANDOM_OFFSET","activeEmojiInteractions","interactions","emoticon","selectLocalAnimatedEmojiEffectByName","timestamps","reaction","selectDefaultReaction","isMessageLocal","sendReaction","isInDocumentGroup","isInAlbum","documentGroupFirstMessageId","reactions","some","isChosen","animationLevel","byKey","ANIMATION_LEVEL_MAX","activeReactions","omit","recentReactions","canSeeList","addMessageReaction","appConfig","defaultReaction","reactors","isGroup","recentTopMessages","msgId","updateStatistics","name","isPercentage","dcId","statisticsDcId","updateStatisticsGraph","areDeepEqual","value1","value2","type1","isArray1","Array","isArray","array1","array2","every","member1","object1","object2","key1","noTopChatsRequest","selectIsChatListed","loadTopChats","newProfilePhoto","closeMessageNotifications","selectChatListType","updateChatListIds","isNotJoined","requestChatUpdate","leaveChat","typingStatus","senderId","isFromScheduled","hasUnreadMention","unreadMentionsCount","notifyAboutMessage","getMessageRecentReaction","messageUpdate","channelId","selectCommonBoxChatId","folderId","ARCHIVED_FOLDER_ID","orderedPinnedIds","isPinned","newOrderedPinnedIds","MAX_ACTIVE_PINNED_CHATS","listIds","active","pinnedId","updateChatListType","folder","chatFoldersById","chatFolders","newChatFoldersById","pick","newOrderedIds","orderedId","folders","recommended","replacedMembers","addedMember","deletedMemberId","shouldUpdate","members","deleteIndex","adminMembers","isOwner","isAdmin","membersCount","photo","formattedText","loadChatJoinRequests","ANIMATION_DELAY","updateWithLocalMedia","isScheduled","currentMessage","video","document","getMessageContent","blobUrl","thumbnail","isPreloadedGlobally","previewBlobUrl","updateScheduledMessage","updateThreadUnread","selectThreadByMessage","originMessage","updateListedAndViewportIds","firstMessageId","isUnreadChatNotLoaded","addViewportId","messagesCount","firstUnreadId","candidateGlobal","updateChatLastMessage","force","currentLastMessage","findLastMessage","deleteMessages","newLastMessage","threadIdsToUpdate","deleteChatMessages","requestThreadInfoUpdate","chatsIdsToUpdate","commonBoxChatId","shouldForceReply","updateThreadInfo","newMessage","selectIsMessageInCurrentMessageList","delayedGlobal","getMessageText","localEmoji","selectLocalAnimatedEmoji","selectLocalAnimatedEmojiEffect","scheduledIds","selectScheduledIds","selectIsChatWithBot","selectScheduledMessages","deleteChatScheduledMessages","thread","markMessageListRead","currentPinnedIds","selectPinnedIds","newPinnedIds","newTheadInfo","messagesById","loadFullChat","scheduledMessages","deleteScheduledMessages","pollId","pollUpdate","selectChatMessageByPollId","updatedPoll","updatedResults","chosenAnswers","chosenAnswer","chosenAnswerIndex","recentVoterIds","totalVoters","newRecentVoterIds","newTotalVoters","targetOption","targetOptionIndex","updatedOption","votersCount","selectIsServiceChatReady","currentReactions","shouldNotify","checkIfReactionAdded","isReaction","flushStatusUpdatesThrottled","pendingStatusUpdates","statusUpdate","targetUser","isBlocked","addBlockedContact","privacy","key","rules","setConfirmPaymentUrl","updateNotifySettings","peerType","shouldShowPreviews","addNotifyException","twoFaSettings","call","connectionState","groupCalls","activeGroupCallId","leaveGroupCall","shouldRemove","removeGroupCall","updateGroupCall","participantsCount","groupCallId","participants","participant","updateGroupCallParticipant","useBeforeUnload","callback","useEffect","onBeforeUnload","metaViewport","querySelector","defaultViewportContent","getAttribute","allowedZoomViewportContent","preventEvent","preventDefault","memo","isForAppBadge","useFolderManagerForUnreadCounters","unreadNotificationsCount","getAllNotificationsCount","updateAppBadge","className","formatIntegerCompact","ConnectionStatus","useConnectionStatus","hasMiddleHeader","isMinimized","isDisabled","isOnline","setIsOnline","useState","navigator","onLine","handleChange","addEventListener","removeEventListener","useBrowserOnline","syncing","online","waitingForNetwork","toLowerCase","connectionStatus","connectionStatusPosition","connectionStatusText","onClick","useLang","dir","isRtl","Spinner","color","Transition","activeKey","Button","size","ANIMATION_LEVEL_OPTIONS","withGlobal","searchQuery","chatsById","isConnectionStatusMinimized","globalSearchChatId","searchDate","theme","selectTheme","isMessageListOpen","areChatsLoaded","contactsFilter","onSearchQuery","onSelectSettings","onSelectContacts","onSelectArchived","onReset","shouldSkipTransition","openTipsChat","setGlobalSearchDate","setSettingOption","setGlobalSearchChatId","hasMenu","LeftColumnContent","selectedSearchDate","useMemo","formatDateToString","archivedUnreadChatsCount","values","total","isChatArchived","withOtherVersions","location","hostname","MainButton","onTrigger","isOpen","ripple","ariaLabel","buildClassName","handleSearchFocus","useCallback","toggleConnectionStatus","handleSelectSaved","handleDarkModeToggle","stopPropagation","newTheme","shouldUseSystemTheme","switchTheme","handleAnimationLevelChange","newLevel","_","classList","toggle","isSearchFocused","searchInputPlaceholder","DropdownMenu","trigger","footer","APP_NAME","APP_REVISION","MenuItem","icon","Switcher","label","checked","noAnimation","langCode","href","FEEDBACK_URL","setPermanentWebVersion","clearWebsync","disableHistoryBack","SearchInput","inputId","parentContainerClassName","focused","spinnerColor","spinnerBackgroundColor","placeholder","autoComplete","canClose","onChange","onFocus","onSpinnerClick","PickerSelectedItem","clickArg","chatOrUserId","ShowTransition","isCustom","orderedFolderIds","activeChatFolder","shouldSkipHistoryAnimations","foldersDispatch","onScreenSelect","loadChatFolders","setActiveChatFolder","transitionRef","useRef","displayedFolders","folderCountersById","folderTabs","ALL_FOLDER_ID","badgeCount","chatsCount","isBadgeActive","notificationsCount","handleSwitchTab","forceOnHeavyAnimation","captureEvents","selectorToPreventScroll","onSwipe","SwipeDirection","isNotInAllTabRef","captureEscKeyListener","useHistoryBack","handleKeyDown","ctrlKey","shiftKey","startsWith","digit","shouldRender","shouldRenderPlaceholder","transitionClassNames","useShowTransition","renderCurrentTab","activeFolder","ChatList","folderType","TabList","tabs","activeTab","onSwitchTab","ref","renderCount","props","LeftSearch","useModuleLoader","Bundles","Loading","ContactList","isShown","onNewPrivateChat","onNewChannel","onNewGroup","isMenuOpen","setIsMenuOpen","fabClassName","tabIndex","Menu","positionX","positionY","autoClose","onClose","TRANSITION_RENDER_COUNT","closeTimeout","onContentChange","isNewChatButtonShown","setIsNewChatButtonShown","isMouseInside","handleSelectSettings","handleSelectContacts","handleSelectNewChannel","handleSelectNewGroup","handleSelectArchived","handleMouseEnter","handleMouseLeave","autoCloseTimeout","shouldRenderUpdateButton","updateButtonClassNames","handleUpdateClick","isAppOutdated","markIsAppOutdated","useFlag","timeout","reload","useAppOutdatedCheck","onMouseEnter","onMouseLeave","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","remove","style","handleMouseMove","newWidth","ceil","clientX","stopDrag","cleanup","offsetWidth","add","useResize","handleSettingsScreenSelect","LAYERS_ANIMATION_NAME","currentScreen","isChannel","onMouseDown","onMouseUp","onDoubleClick","setSize","handleResize","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","canViewStatistics","pendingJoinRequests","canExpandActions","joinChannel","openLocalTextSearch","restartBot","openCallFallbackConfirm","requestNextManagementScreen","menuButtonRef","menuPosition","setMenuPosition","handleHeaderMenuOpen","rect","getBoundingClientRect","right","bottom","handleHeaderMenuClose","handleHeaderMenuHide","handleSubscribeClick","handleStartBot","handleRestartBot","handleJoinRequestsClick","ManagementScreens","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","renderMessageSummary","isUnpinDialogOpen","openUnpinDialog","closeUnpinDialog","handleUnpinMessage","ConfirmDialog","confirmLabel","confirmHandler","getPictogramDimensions","src","alt","renderPictogram","RippleEffect","scaleImage","image","ratio","outputType","Blob","URL","createObjectURL","img","Image","onload","scale","blob","Error","finally","revokeObjectURL","steppedScale","bitmap","createImageBitmap","resizeWidth","resizeHeight","resizeQuality","res","canvas","createElement","ctx","getContext","transferFromImageBitmap","drawImage","toBlob","oc","octx","mul","cur","LOGO_DIMENSIONS","MINIMAL_SIZE","audio","voice","fileName","artist","performer","getTranslation","album","getChatTitle","audioCoverHash","getAudioHasCover","avatarHash","getChatAvatarHash","media","thumbnailSizes","preferred","AVATAR_FULL_DIMENSIONS","getCoverSize","fn","deps","defaultValue","setIsLoading","setError","setResult","wasCancelled","telegramLogoPath","resizeImage","makeGoodArtwork","useAsync","buildMediaMetadata","artwork","noUi","setAudioPlayerVolume","setAudioPlayerPlaybackRate","setAudioPlayerMuted","isVoice","senderName","mediaData","mediaMetadata","useMessageMediaMetadata","playPause","stop","isPlaying","requestNextTrack","requestPreviousTrack","isFirst","isLast","setVolume","toggleMuted","setPlaybackRate","useAudioPlayer","makeTrackId","getMediaDuration","isVoicePlaying","handleClick","handleClose","clearMediaSession","handleVolumeChange","handleVolumeClick","handlePlaybackClick","volumeIcon","renderText","renderAudio","subtitle","renderVoice","withClickPropagation","RangeSlider","bold","groupCall","selectChatGroupCall","usersById","isLoaded","isCallNotEmpty","hasPinnedOffset","joinGroupCall","subscribeToGroupCallUpdates","handleJoinGroupCall","fetchedParticipants","isUser","subscribed","p","Avatar","openAddContactDialog","blockContact","reportSpam","deleteChat","leaveChannel","deleteChatUser","deleteHistory","toggleChatArchived","hideChatReportPanel","isBlockUserModalOpen","openBlockUserModal","closeBlockUserModal","shouldReportSpam","setShouldReportSpam","shouldDeleteChat","setShouldDeleteChat","isAutoArchived","canReportSpam","canAddContact","canBlockContact","isBasicGroup","handleAddContact","handleConfirmBlock","contactId","handleCloseReportPanel","handleChatReportSpam","isText","getUserFirstOrLastName","getUserFullName","isButtonsInOneRow","confirmIsDestructive","Checkbox","onCheck","audioMessage","pinnedIds","state","isSelectModeActive","isChatWithBot","currentTransitionKey","assign","pinnedMessageId","topMessageSender","selectForwardedSender","pinnedMessageIds","canUnpin","firstPinnedMessage","isReady","openChatWithInfo","pinMessage","openPreviousChat","toggleLeftColumn","isBackButtonActive","pinnedMessageIndex","setPinnedMessageIndex","pinnedMessage","pinnedMessagesCount","chatTitleLength","topMessageTitle","useEnsureMessage","useWindowSize","isLeftColumnHideable","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","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","hasChatSettings","shouldShowChatReportPanel","chatReportPanelClassNames","renderingChatSettings","useCurrentOrPrev","shouldRenderAudioPlayer","audioPlayerClassNames","renderingAudioMessage","shouldRenderPinnedMessage","pinnedMessageClassNames","renderingPinnedMessage","renderingPinnedMessagesCount","renderingCanUnpin","renderingPinnedMessageTitle","canRevealTools","componentEl","renderBackButton","asClose","withUnreadCounter","isAudioPlayerRendered","PrivateChatInfo","withDots","withFullInfo","withMediaViewer","withUpdatingStatus","noRtl","GroupChatInfo","getMessageKey","isAlbum","messageOrAlbum","groupMessages","currentAlbum","currentSenderGroup","currentDateGroup","originalDate","datetime","getDayStartAt","senderGroups","dateGroups","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","stretchFactor","finalWidth","finalHeight","isSmall","accumulate","list","initValue","accumulator","item","clamp","num","low","high","calculateContainerSize","layout","styles","dimensions","sides","calculateAlbumLayout","ratios","getRatios","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","QUICK_REACTION_AREA_WIDTH","QUICK_REACTION_AREA_HEIGHT","GROUP_MESSAGE_HOVER_ATTRIBUTE","useOuterHandlers","selectMessage","isInSelectMode","canReply","isProtected","onContextMenu","handleBeforeContextMenu","isContextMenuShown","contentRef","shouldHandleMouseLeave","sendDefaultReaction","isQuickReactionVisible","markQuickReactionVisible","unmarkQuickReactionVisible","isSwiped","markSwiped","unmarkSwiped","doubleTapTimeoutRef","startedAt","onRelease","handleMouseDown","preventMessageInputBlur","clearInterval","pageX","pageY","handleDoubleTap","target","contains","handleTap","handleContextMenu","stopEvent","matches","handleDoubleClick","handleContentDoubleClick","container","clientY","isVisibleX","isVisibleY","handleSendQuickReaction","currentTarget","lastGroupElement","getLastElementInDocumentGroup","removeAttribute","handleDocumentGroupMouseLeave","handleDocumentGroupMouseEnter","setAttribute","nextElementSibling","ContextMenuContainer","targetUserIds","targetChatId","targetMessageId","targetMessage","selectIsMessageFocused","focusedMessage","isChat","senderUser","senderChat","observeIntersection","isEmbedded","appearanceOrder","isLastInList","useOnIntersect","noAppearanceAnimation","markShown","targetUsers","renderActionMessageText","asTextWithSpoilers","isContextMenuOpen","contextMenuPosition","handleContextMenuClose","handleContextMenuHide","useContextMenuHandlers","getMessageHtmlId","customText","isIntersecting","useIsIntersecting","isRoundVideo","getMessageRoundVideo","senderTitle","draggable","activeReaction","isInMeta","stopActiveReaction","r","centerIconId","effectId","mediaDataCenterIcon","mediaDataEffect","shouldPlay","shouldRenderAnimation","animationClassNames","handleEnded","isAnimationLoaded","markAnimationLoaded","unmarkAnimationLoaded","shouldRenderStatic","ReactionStaticEmoji","AnimatedSticker","animationData","play","noLoop","onLoad","onEnded","outgoingStatus","signature","withReactions","withReactionOffset","reactionMessage","isActivated","markActivated","createDateTime","formatDateTimeToString","editDateTime","isEdited","editDate","forwardedDateTime","views","formatTime","MessageOutgoingStatus","observeIntersectionForPlaying","shouldLoop","isModalOpen","openModal","closeModal","isLottie","isVideo","canDisplayVideo","IS_WEBM_SUPPORTED","isMemojiSticker","NO_STICKER_SET_ID","shouldLoad","mediaHash","previewMediaHash","previewUrl","getMessageMediaFormat","isMediaLoaded","isLottieLoaded","markLottieLoaded","isMediaReady","useMediaTransition","getStickerDimensions","thumbClassName","stickerClassName","safePlay","autoPlay","playsInline","loop","muted","fromSticker","useBlurredMediaThumbRef","fullMediaData","useCanvasBlur","IS_CANVAS_FILTER_SUPPORTED","SELECTED_APPENDIX_COLORS","dark","outgoing","incoming","light","getCustomAppendixBg","inSelectMode","isSelected","getImageData","getAppendixColorFromImage","canAutoLoad","uploadProgress","nonInteractive","shouldAffectAppendix","isDownloading","onCancelUpload","localBlobUrl","isLoadAllowed","setIsLoadAllowed","loadProgress","useMediaWithLoadProgress","thumbRef","downloadProgress","isUploading","isTransferring","transferProgress","getMediaTransferState","wasLoadDisabled","usePrevious","shouldRenderSpinner","spinnerClassNames","shouldRenderDownloadButton","downloadButtonClassNames","isAllowed","contentEl","appendixBg","setProperty","CUSTOM_APPENDIX_ATTRIBUTE","ProgressSpinner","useVideoAutoPause","playerRef","canPlay","wasPlaying","paused","canPlayRef","freezePlaying","unfreezePlaying","unfreezePlayingOnRaf","fastRaf","useBackgroundMode","useHeavyAnimationCheck","canAutoPlay","videoRef","getMessageWebPageVideo","isPlayAllowed","setIsPlayAllowed","previewClassNames","isInline","isBuffered","bufferingHandlers","useBuffering","shouldRenderPlayButton","playButtonClassNames","playProgress","setPlayProgress","handleTimeUpdate","currentTime","duration","useVideoCleanup","cancelMessageMediaDownload","onTimeUpdate","isGif","formatMediaDuration","contact","countryList","phoneCodes","phoneCodeList","formatPhoneNumberWithCode","getPercentage","toFixed","answer","voteResults","maxVotersCount","correctResults","shouldAnimate","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","inPreview","onMediaClick","onCancelMediaTransfer","webPage","getMessageWebPage","isSquarePhoto","handleMediaClick","siteName","displayUrl","isMediaInteractive","truncatedDescription","trimText","SafeLink","getMessageInvoice","amount","currency","isTest","photoUrl","formatCurrency","VENUE_COLORS","entries","arts_entertainment","building","education","event","food","home","nightlife","parks_outdoors","shops","travel","work","RANDOM_COLORS","variant","animation","classNames","MOVE_THRESHOLD","DEFAULT_MAP_CONFIG","zoom","SVG_PIN","__html","forceUpdate","useForceUpdate","getMessageLocation","geo","serverTime","isExpired","isGeoLiveExpired","secondsBeforeEnd","period","point","setPoint","shouldRenderText","buildStaticMapHash","prevMediaBlobUrl","mapBlobUrl","isPeerUser","avatarUser","avatarChat","accuracyRadiusPx","accuracyRadius","lat","cos","getMetersPerPixel","updateCountdown","timeLeft","formatCountdownShort","long","useTimeout","useInterval","prepareMapUrl","open","pinClassName","dangerouslySetInnerHTML","heading","str","prevHash","currVal","charCodeAt","getVenueColor","venueType","getVenueIconUrl","mapPin","renderPin","renderOverlay","address","formatLastUpdated","renderInfo","withSelectControl","WrappedComponent","ownProps","selectIsMessageSelected","handleMessageSelect","newProps","dims","PhotoWithSelect","Photo","VideoWithSelect","Video","activeDownloadIds","selectActiveDownloadIds","uploadsById","hasCustomAppendix","albumLayout","cancelSendingMessage","mediaCount","handleCancelUpload","containerWidth","containerHeight","fileUpload","selectCanAutoLoadMedia","selectCanAutoPlayMedia","stopPrevious","playingProgressRef","shouldSpinnerRender","setIsActivated","setProgress","svgCenter","ROUND_VIDEO_DIMENSIONS_PX","playerEl","playingProgressEl","stopPlaying","capturePlaying","stopCurrentAudio","videoClassName","recentReplierIds","recentRepliers","peerId","hasUnread","recentReactors","recentReaction","isOutside","metaChildren","localSticker","soundId","playKey","useAnimatedEmoji","localStickerAnimationData","setLocalStickerAnimationData","getAnimationData","quality","APPENDIX_OWN","APPENDIX_NOT_OWN","withSenderName","withAvatar","isLastInDocumentGroup","viaBotId","replyToChatId","isRepliesChat","isChatWithRepliesBot","chatUsername","forceSenderName","isAnonymousOwnMessage","canShowSender","originSender","botSender","threadTopMessageId","isThreadTop","shouldHideReply","replyMessageSender","selectUploadProgress","isForwarding","highlight","singleEmoji","getMessageSingleEmoji","selectIsDownloading","actualThreadInfo","selectIsMessageProtected","isSingleEmoji","animatedEmoji","selectAnimatedEmoji","animatedEmojiEffect","selectAnimatedEmojiEffect","animatedEmojiSoundId","selectAnimatedEmojiSound","isGroupSelected","selectIsDocumentGroupSelected","isPinnedList","canAutoLoadMedia","canAutoPlayMedia","autoLoadFileMaxSizeMb","shouldLoopStickers","selectShouldLoopStickers","selectOutgoingStatus","observeIntersectionForBottom","observeIntersectionForMedia","observeIntersectionForAnimatedStickers","areReactionsInMeta","noComments","isFirstInGroup","isLastInGroup","isFirstInDocumentGroup","clickInlineButton","bottomMarkerRef","isLocal","hasReply","isReplyMessage","hasThread","getMessageCustomShape","hasAnimatedEmoji","hasReactions","areReactionsEmpty","asForwarded","isLinkedChannelPost","isInDocumentGroupNotFirst","isInDocumentGroupNotLast","canShowActionButton","canForward","canFocus","isChannelPost","fromMessageId","withCommentButton","withQuickReactionButton","messageSender","avatarPeer","senderPeer","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","isGeoLiveActive","isMedia","isMediaWithNoText","isViaBot","isRound","buildContentClassName","withAppendix","textParts","renderMessageText","metaPosition","reactionsPosition","calculatedWidth","noMediaCorners","extraPadding","adminTitle","metaSafeAuthorWidth","renderReactionsAndMeta","meta","onMouseMove","isAvatarPeerUser","hiddenName","renderAvatar","textContentClass","senderColor","getUserColorKey","renderSenderName","AnimatedEmoji","effect","forceLoadPreview","Audio","AudioOrigin","isSelectable","onPlay","onReadMedia","Document","renderContent","isBot","channel","viewSponsoredMessage","openChatByInvite","startBot","shouldObserve","observe","useIntersectionObserver","rootRef","debounceMs","threshold","chatInviteTitle","chatInviteHash","messageGroups","isViewportNewest","withUsers","anchorIdRef","memoUnreadDividerBeforeIdRef","memoFirstUnreadIdRef","isScrollingRef","isScrollPatchNeededRef","hasLinkedChat","isSchedule","onFabToggle","onNotchToggle","openHistoryCalendar","observeIntersectionForReading","throttleMs","margin","freeze","freezeForReading","unfreeze","unfreezeForReading","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","useOnChange","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","noContextMenu","isGroupChatJustCreated","renderScheduled","renderSavedMessages","renderGroup","runDebouncedForScroll","selectCurrentMessageIds","restrictionReason","focusingId","withLastMessageWhenPreloading","chatBot","botDescription","isChatLoaded","isChannelChat","isGroupChat","isChatGroup","threadFirstMessageId","selectFirstMessageId","linkedChatId","hasTools","canPost","withBottomShift","setScrollOffset","loadSponsoredMessages","loadMessageReactions","copyMessagesByIds","scrollOffsetRef","selectScrollOffset","anchorTopRef","listItemElementsRef","memoFocusingIdRef","isScrollTopJustUpdatedRef","shouldAnimateAppearanceRef","setContainerHeight","onTickEnd","handleCopy","getMessageIdsForSelectedText","useNativeCopySelectedMessages","listedMessages","orderBy","loadMoreAround","isScrolled","updateStickyDates","markIsScrolled","runDebounced","useDebounce","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","backgroundColor","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","insertHtmlInSelection","html","selection","getSelection","getRangeAt","rangeCount","range","deleteContents","fragment","createContextualFragment","lastInsertedNode","lastChild","insertNode","setStartAfter","setEndAfter","collapse","removeAllRanges","addRange","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","useDebouncedMemo","resolverFn","ms","dependencies","setValue","isFrozen","INLINE_BOT_QUERY_REGEXP","HAS_NEW_LINE","MEMO_NO_RESULT","canShowHelp","usernameLowered","tempEl","runThrottled","RE_COMMAND","DeleteMessageModal","openTimeout","isFirstTimeActivation","onActivate","buttonProps","isButtonVisible","canAttachMedia","canAttachPolls","onFileSelect","onPollCreate","isAttachMenuOpen","openAttachMenu","closeAttachMenu","markMouseInside","useMouseInside","handleFileSelect","files","handleQuickSelect","openSystemFilesDialog","CONTENT_TYPES_WITH_PREVIEW","handleDocumentSelect","ariaControls","hasPopup","noCloseOnBackdrop","ariaLabelledBy","SymbolMenu","InlineBotTooltip","MentionTooltip","StickerTooltip","BotCommandTooltip","isKeyboardSingleUse","forceOpen","markForceOpen","unmarkForceOpen","keyboardButtons","noCompact","forwardMessageIds","forwardedMessagesCount","onClear","exitForwardMode","canAnimate","useAsyncRendering","clearEmbedded","handleMessageClick","faded","AttachmentModal","BotCommandMenu","PollModal","DropArea","RE_LINK","RegExp","RE_LINK_TEMPLATE","messageText","toggleMessageWebPage","linkEntity","ApiMessageEntityTypes","textMatch","renderingWebPage","webPageWithoutPhoto","messageStub","SendAsMenu","MainButtonState","VOICE_RECORDING_FILENAME","REPLIES_USER_ID","messageWithActualBotKeyboard","selectNewestMessageWithBotKeyboardButtons","shouldSuggestStickers","baseEmojiKeywords","BASE_EMOJI_KEYWORD_LANG","botKeyboardMessageId","keyboardMessage","defaultSendAsId","anonymous","sendAsUser","selectEditingScheduledDraft","editingMessage","canScheduleUntilOnline","selectCanScheduleUntilOnline","withScheduledButton","shouldSchedule","botKeyboardPlaceholder","keyboardPlaceholder","stickersForEmoji","groupChatMembers","topInlineBotIds","isInlineBotLoading","chatBotCommands","botCommands","dropAreaState","onDropHide","clearDraft","setStickerSearchQuery","setGifSearchQuery","closePollModal","addRecentEmoji","sendInlineBotResult","loadSendAs","appendixRef","setHtml","htmlRef","useStateRef","lastMessageSendTimeSeconds","prevDropAreaState","canShowSendAs","isSymbolMenuForced","forceShowSymbolMenu","cancelForceShowSymbolMenu","sendMessageAction","useSendMessageAction","handleScheduleCancel","requestCalendar","calendar","useSchedule","shouldAnimateSendAsButtonRef","prevChatId","prevSendAsIds","setAttachments","isBotKeyboardOpen","openBotKeyboard","closeBotKeyboard","isBotCommandMenuOpen","openBotCommandMenu","closeBotCommandMenu","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","SEND_MESSAGE_ACTION_INTERVAL","mainButtonState","Edit","Schedule","Send","Record","canShowCustomSendMenu","isMentionTooltipOpen","closeMentionTooltip","insertMention","mentionFilteredUsers","useMentionTooltip","isInlineBotTooltipOpen","inlineBotId","isInlineBotTooltipGallery","inlineBotSwitchPm","inlineBotResults","closeTooltip","closeInlineBotTooltip","inlineBotHelp","loadMore","loadMoreForInlineBot","queryInlineBot","resetInlineBot","markIsOpen","unmarkIsOpen","innerText","getPlainText","parseBotQuery","prevQuery","prevUsername","useInlineBotTooltip","isBotCommandTooltipOpen","close","closeBotCommandTooltip","filteredBotCommands","botTooltipCommands","setFilteredBotCommands","getFilteredCommands","nextFilteredBotCommands","prepareForRegExp","substr","useBotCommandTooltip","isCustomSendMenuOpen","canSendStickers","canSendGifs","canAttachEmbedLinks","getAllowedAttachmentOptions","isChatAdmin","slowMode","getChatSlowModeOptions","isStickerTooltipOpen","closeStickerTooltip","cleanHtml","trim","clearStickersForEmoji","IS_EMOJI_SUPPORTED","parseEmojiOnlyString","hasStickers","useStickerTooltip","isEmojiTooltipOpen","closeEmojiTooltip","filteredEmojis","insertEmoji","useEmojiTooltip","insertTextAndUpdateCursor","newHtml","selectionRange","isSelectionInsideInput","dispatchEvent","Event","bubbles","focusEditableElement","removeSymbol","execCommand","tempInput","contentEditable","textLength","createRange","setStart","setEnd","removeChild","deleteLastCharacterOutsideSelection","resetComposer","shouldPreserveInput","stopRecordingVoiceRef","handleEditComplete","handleEditCancel","editedMessage","editMessage","setEditingDraft","prevEditedMessage","getTextWithEntitiesAsHtml","edited","restoreNewDraftAfterEditing","hasMessageMedia","handleBlur","useEditing","saveDraft","updateDraft","draftChatId","draftThreadId","currentHtml","runDebouncedForSaveDraft","DRAFT_DEBOUNCE","prevThreadId","prevHtml","useDraft","handlePaste","clipboardData","input","activeElement","EDITABLE_INPUT_MODAL_ID","pastedText","getData","substring","items","getFilesFromDataTransferItems","newAttachments","all","file","useClipboardPaste","handleEmbeddedClear","handleAppendFiles","handleClearAttachment","handleSend","currentAttachments","record","maxLength","extraLength","textParams","nowSeconds","secondsSinceLastMessage","nextSendDateNotReached","nextSendDate","seconds","secondsRemaining","isSlowMode","handleActivateBotCommandMenu","handleActivateSymbolMenu","handleMessageSchedule","args","restArgs","isScheduleRequested","handleGifSelect","handleInlineBotSelect","inlineResult","handleBotCommandSelect","handlePollSend","handleSendSilent","handleSearchOpen","handleSymbolMenuOpen","handleSendAsMenuOpen","handleAllScheduledClick","mainButtonHandler","areVoiceMessagesNotAllowed","renderedEditedMessage","scheduledDefaultDate","setSeconds","setMilliseconds","scheduledMaxDate","setFullYear","getFullYear","sendButtonAriaLabel","symbolMenuButtonClassName","handleSendScheduled","onSend","DropAreaState","withQuick","onHide","caption","onCaptionUpdate","onSendSilent","onSendScheduled","onFileAppend","shouldBeAnonimous","selectedSendAsId","onInsertUserName","filteredUsers","onSelectResult","isSavedMessages","withUsername","MessageInput","forcedPlaceholder","canAutoFocus","shouldSuppressFocus","shouldSuppressTextFormatter","onUpdate","onSuppressedFocus","formatVoiceRecordDuration","onStickerSelect","emojis","onEmojiSelect","onGifSelect","onRemoveSymbol","onSearchOpen","onSendSchedule","MobileSearch","MessageSelectToolbar","UnpinAllMessagesModal","PaymentModal","ReceiptModal","SeenByModal","EmojiInteractionAnimation","ReactorListModal","CLOSE_ANIMATION_DURATION","isImage","kind","isBlurred","isBackgroundBlurred","background","customBackground","patternColor","themes","isMobileSearchActive","isReceiptModalOpen","isSeenByModalOpen","isReactorListModalOpen","getCanPostInChat","isBotNotStarted","isPinnedMessageList","isScheduledMessageList","areChatSettingsLoaded","currentUserBannedRights","defaultBannedRights","hasPinnedOrAudioPlayer","loadUser","loadChatSettings","closePaymentModal","clearReceipt","setDropAreaState","isFabShown","setIsFabShown","isNotchShown","setIsNotchShown","isUnpinModalOpen","setIsUnpinModalOpen","renderingChatId","usePrevDuringAnimation","renderingThreadId","renderingMessageListType","renderingCanSubscribe","renderingCanStartBot","renderingCanRestartBot","renderingCanPost","renderingHasTools","renderingIsFabShown","renderingIsChannel","prevTransitionKey","handleOpenEnd","handleSlideStop","withAnimations","setIsReady","willSwitchMessageList","propertyName","useIsReady","ANIMATION_LEVEL_MIN","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","teactOrderKey","HeaderContent","isProfile","isManagement","messageSearchQuery","stickerSearchQuery","selectCurrentStickerSearch","gifSearchQuery","selectCurrentGifSearch","getCanAddContact","canManage","isEditingInvite","isColumnOpen","isSearch","isStatistics","isStickerSearch","isGifSearch","isPollResults","isAddingChatMembers","profileState","managementScreen","shouldSkipAnimation","setLocalTextSearchQuery","searchTextMessagesLocal","toggleManagement","toggleStatistics","setEditingExportedInvite","deleteExportedChatInvite","backButtonRef","isDeleteDialogOpen","openDeleteDialog","closeDeleteDialog","handleEditInviteClick","handleDeleteInviteClick","handleMessageSearchQueryChange","handleStickerSearchQueryChange","handleGifSearchQueryChange","setShouldSkipTransition","contentKey","ProfileState","Profile","SharedMedia","MemberList","Search","PollResults","StickerSearch","GifSearch","AddingMembers","ManageInitial","ManageChatPrivacyType","ManageDiscussion","ManageChannelSubscribers","ManageGroupPermissions","ManageChatAdministrators","ManageGroupRemovedUsers","ManageChannelRemovedUsers","ManageGroupUserPermissionsCreate","ManageGroupUserPermissions","ManageGroupRecentActions","ManageGroupAdminRights","ManageGroupNewAdminRights","ManageGroupMembers","ManageInvites","ManageEditInvite","ManageGroupAddAdmins","ManageReactions","ManageInviteInfo","ManageJoinRequests","Statistics","renderingContentKey","isBackButton","buttonClassName","autoFocusSearch","renderHeaderContent","useInfiniteScrollForLoadableItems","currentResultType","handleLoadMore","itemIds","getMore","useInfiniteScroll","MEMBERS_SLICE","useInfiniteScrollForSharedMedia","forSharedMediaType","messageIdsRef","getMessageContentIds","runThrottledForScroll","isScrollingProgrammatically","TABS","buildInfiniteScrollItemSelector","resultType","mediaSearchType","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","canRenderContent","InfiniteScroll","itemSelector","sensitiveArea","PROFILE_SENSITIVE_AREA","preloadBackwards","noScrollRestoreOnTop","noFastList","onLoadMore","ProfileInfo","ChatExtra","renderProfileInfo","shouldRestoreHeight","onStart","noSpinner","NothingFound","Media","withDate","smaller","onDateClick","WebLink","onMessageClick","getSenderName","ListItem","contextActions","memberId","handler","forceShowSelf","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","nextManagementScreen","selectRightColumnContentKey","isChatSelected","toggleChatInfo","closePollResults","addChatMembers","setOpenedInviteInfo","setProfileState","setManagementScreen","selectedChatMemberId","setSelectedChatMemberId","isPromotedByCurrentUser","setIsPromotedByCurrentUser","isScrolledDown","isOverlaying","shouldScrollUp","handleSelectChatMember","isPromoted","handleAppendingChatMembers","onChatMemberSelect","MediaViewer","download","click","startedDownloads","downloadHash","getMessageContentFilename","Notifications","Dialogs","ForwardPicker","SafeLinkModal","HistoryCalendar","GroupCall","ActiveCallHeader","CallFallbackConfirm","NewContactModal","notificationInterval","DEBUG_isLogged","updateIcon","asUnread","updatePageTitle","nextTitle","wasTimeFormatSetManually","authState","isMediaViewerOpen","selectIsMediaViewerOpen","isForwardModalOpen","selectIsForwardModalOpen","hasNotifications","hasDialogs","isHistoryCalendarOpen","isServiceChatReady","isCallFallbackConfirmOpen","isFallbackConfirmOpen","newContactUserId","newContactByPhoneNumber","sync","loadNotificationSettings","loadNotificationExceptions","updateIsOnline","loadTopInlineBots","loadEmojiKeywords","loadCountryList","loadAvailableReactions","loadAddedStickers","ensureTimeFormat","openStickerSetShortName","checkVersionNotification","loadAppConfig","LOCATION_HASH","processDeepLink","decodeURIComponent","middleColumnTransitionClassNames","rightColumnTransitionClassNames","prevIsLeftColumnShown","dispatchHeavyAnimationEnd","waitForTransitionEnd","prevIsRightColumnShown","initialUnread","setInterval","INACTIVE_MARKER","newUnread","PAGE_TITLE","handleStickerSetModalClose","usePreventPinchZoomGesture","onDrop","onDragOver","initApi"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/742.e09d8d2bec0ce4cf0543.js b/dist/742.b2feed9283c594eb9e2f.js similarity index 99% rename from dist/742.e09d8d2bec0ce4cf0543.js rename to dist/742.b2feed9283c594eb9e2f.js index e4d3369c..88ce6d5d 100644 --- a/dist/742.e09d8d2bec0ce4cf0543.js +++ b/dist/742.b2feed9283c594eb9e2f.js @@ -1,2 +1,2 @@ -(()=>{var e,t,n={1742:(e,t,n)=>{"use strict";var s={};n.r(s),n.d(s,{Type:()=>Gt,clear:()=>Wt,fetch:()=>Kt,save:()=>zt});var a={};n.r(a),n.d(a,{addChatMembers:()=>Zn,answerCallbackButton:()=>Ki,blockContact:()=>vi,checkChatUsername:()=>Ia,checkPassword:()=>Oa,checkUsername:()=>fi,clearDraft:()=>wn,clearPassword:()=>Ha,createChannel:()=>In,createGroupCall:()=>ti,createGroupChat:()=>kn,deleteChannel:()=>Mn,deleteChat:()=>Sn,deleteChatFolder:()=>xn,deleteChatMember:()=>Yn,deleteChatUser:()=>An,deleteContact:()=>ea,deleteExportedChatInvite:()=>ka,deleteHistory:()=>ws,deleteMessages:()=>ys,deleteRevokedExportedChatInvites:()=>Ra,deleteScheduledMessages:()=>bs,destroy:()=>Yt,discardGroupCall:()=>$a,disconnect:()=>en,downloadMedia:()=>on,editChatFolder:()=>Tn,editChatPhoto:()=>Rn,editExportedChatInvite:()=>Pa,editGroupCallParticipant:()=>Ja,editGroupCallTitle:()=>Qa,editMessage:()=>ps,exportChatInvite:()=>Ma,exportGroupCallInvite:()=>Xa,faveSticker:()=>ca,fetchAnimatedEmojiEffects:()=>ua,fetchAnimatedEmojis:()=>da,fetchAppConfig:()=>qi,fetchAuthorizations:()=>Ci,fetchBlockedContacts:()=>wi,fetchChannelStatistics:()=>oo,fetchChat:()=>_n,fetchChatFolders:()=>Dn,fetchChatInviteImporters:()=>Ua,fetchChatSettings:()=>hn,fetchChats:()=>pn,fetchCommonChats:()=>js,fetchContactList:()=>Qs,fetchContentSettings:()=>Fi,fetchCountryList:()=>Hi,fetchCurrentUser:()=>ln,fetchEmojiKeywords:()=>ba,fetchExportedChatInvites:()=>Sa,fetchFavoriteStickers:()=>oa,fetchFeaturedStickers:()=>ra,fetchFullChat:()=>fn,fetchFullUser:()=>Ws,fetchGroupCallParticipants:()=>Za,fetchGroupStatistics:()=>ro,fetchGroupsForDiscussion:()=>$n,fetchInlineBot:()=>Wi,fetchInlineBotResults:()=>ji,fetchLangPack:()=>Ei,fetchLangStrings:()=>Di,fetchLanguages:()=>Ui,fetchMembers:()=>jn,fetchMessage:()=>ls,fetchMessageReactions:()=>eo,fetchMessageReactionsList:()=>to,fetchMessages:()=>cs,fetchNearestCountry:()=>$s,fetchNotificationExceptions:()=>Pi,fetchNotificationSettings:()=>Mi,fetchPinnedMessages:()=>Vs,fetchPrivacySettings:()=>Bi,fetchProfilePhotos:()=>ta,fetchRecentStickers:()=>ia,fetchRecommendedChatFolders:()=>Bn,fetchSavedGifs:()=>pa,fetchScheduledHistory:()=>Bs,fetchSeenBy:()=>Ns,fetchSendAs:()=>Fs,fetchSponsoredMessages:()=>qs,fetchStatisticsAsyncGraph:()=>co,fetchStickerSets:()=>aa,fetchStickers:()=>la,fetchStickersForEmoji:()=>ya,fetchTopInlineBots:()=>zi,fetchTopUsers:()=>Js,fetchUsers:()=>Xs,fetchWallpapers:()=>yi,fetchWebPagePreview:()=>ks,findFirstMessageIdAfterDate:()=>Ds,forwardMessages:()=>Es,getAvailableReactions:()=>Zi,getChatByPhoneNumber:()=>Nn,getChatByUsername:()=>Fn,getGroupCall:()=>ja,getPasswordInfo:()=>La,getPaymentForm:()=>ci,getReceipt:()=>li,hideAllChatJoinRequests:()=>Da,hideChatJoinRequest:()=>Ea,hideChatReportPanel:()=>Ba,importChatInvite:()=>ns,importContact:()=>Zs,installStickerSet:()=>ha,joinChannel:()=>Cn,joinGroupCall:()=>ei,joinGroupCallPresentation:()=>ni,leaveChannel:()=>Pn,leaveGroupCall:()=>Ya,leaveGroupCallPresentation:()=>ai,loadPollOptionResults:()=>Us,markMessageListRead:()=>Cs,markMessagesRead:()=>As,migrateChat:()=>Qn,openChatByInvite:()=>Xn,pinMessage:()=>ms,provideAuthCode:()=>Vt,provideAuthPassword:()=>Nt,provideAuthPhoneNumber:()=>xt,provideAuthRegistration:()=>Ft,provideRecoveryEmailCode:()=>za,registerDevice:()=>Ti,reportMessages:()=>vs,reportSpam:()=>na,requestChatUpdate:()=>yn,requestThreadInfoUpdate:()=>Ss,rescheduleMessage:()=>fs,restartAuth:()=>Lt,restartAuthWithQr:()=>qt,saveDefaultSendAs:()=>Ls,saveDraft:()=>bn,saveGif:()=>fa,searchChats:()=>mn,searchGifs:()=>_a,searchMessagesGlobal:()=>Ms,searchMessagesLocal:()=>Ps,searchStickers:()=>ga,sendEmojiInteraction:()=>Xi,sendInlineBotResult:()=>$i,sendMessage:()=>us,sendMessageAction:()=>Is,sendPaymentForm:()=>ri,sendPollVote:()=>Rs,sendReaction:()=>Yi,sendScheduledMessages:()=>Ts,sendWatchingEmojiInteraction:()=>Qi,setChatEnabledReactions:()=>ss,setChatUsername:()=>Ca,setDefaultReaction:()=>no,setDiscussionGroup:()=>Jn,setPrivacySettings:()=>Vi,startBot:()=>Ji,terminateAllAuthorizations:()=>Si,terminateAuthorization:()=>Ai,toggleChatArchived:()=>En,toggleChatPinned:()=>Un,toggleDialogUnread:()=>Vn,toggleGroupCallStartSubscription:()=>si,toggleIsProtected:()=>as,togglePreHistoryHidden:()=>qn,toggleSignatures:()=>Wn,unblockContact:()=>Ii,uninstallStickerSet:()=>ma,unpinAllMessages:()=>_s,unregisterDevice:()=>xi,updateChatAbout:()=>zn,updateChatAdmin:()=>Gn,updateChatDefaultBannedRights:()=>On,updateChatMemberBannedRights:()=>Hn,updateChatMutedState:()=>vn,updateChatTitle:()=>Kn,updateContact:()=>Ys,updateContactSignUpNotification:()=>ki,updateContentSettings:()=>Li,updateIsOnline:()=>Ni,updateNotificationSettings:()=>Ri,updatePassword:()=>Ga,updatePrivateLink:()=>Aa,updateProfile:()=>pi,updateProfilePhoto:()=>mi,updateRecoveryEmail:()=>Ka,updateUsername:()=>hi,uploadProfilePhoto:()=>_i,uploadWallpaper:()=>bi,validateRequestedInfo:()=>oi,viewSponsoredMessage:()=>Os});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"]),l=(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 d,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){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"image/jpeg";const s=t?"":`data:${n};base64,`;return`${s}${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 v(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 C={localMessages:{},chats:{},users:{},messages:{},documents:{},stickerSets:{},photos:{},webDocuments:{}},A="application/x-tgsticker",S="video/webm";function P(e){if(e instanceof g.Api.DocumentEmpty)return;const{mimeType:t}=e,n=e.attributes.find((e=>e instanceof g.Api.DocumentAttributeSticker)),s=(t===A||t===S)&&e.attributes.find((e=>e instanceof g.Api.DocumentAttributeFilename));if(!n&&!s)return;const a=t===A,i=t===S,o=e.attributes.find((e=>e instanceof g.Api.DocumentAttributeImageSize)),r=e.attributes.find((e=>e instanceof g.Api.DocumentAttributeVideo)),c=o||r,l=n&&n.stickerset instanceof g.Api.InputStickerSetID?n.stickerset:void 0,d=null==n?void 0:n.alt,u=e.thumbs&&e.thumbs.find((e=>e instanceof g.Api.PhotoCachedSize));if(!(t!==S||self.isWebmSupported||u||e.thumbs&&e.thumbs.find((e=>e instanceof g.Api.PhotoSize))))return;const p=e.thumbs&&e.thumbs.find((e=>e instanceof g.Api.PhotoPathSize)),f=u?function(e){const{w:t,h:n,bytes:s}=e;return{dataUri:m(s,void 0,"image/webp"),width:t,height:n}}(u):p&&c?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}}(p,c):void 0,{w:h,h:_}=u||c||{};return{id:String(e.id),stickerSetId:l?String(l.id):"NO_STICKER_SET",stickerSetAccessHash:l&&String(l.accessHash),emoji:d,isLottie:a,isVideo:i,width:h,height:_,thumbnail:f}}function M(e){const{archived:t,animated:n,installedDate:s,videos:a,id:i,accessHash:o,title:r,thumbs:c,count:l,shortName:d}=e;return{archived:t,isLottie:n,isVideos:a,installedDate:s,id:String(i),accessHash:String(o),title:r,hasThumbnail:Boolean(null==c?void 0:c.length),count:l,shortName:d}}function k(e){const t=M(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=P(e);n&&(t.covers.push(n),C.documents[String(e.id)]=e)}})),t}function R(e,t){let n=0;const s=new Array(t),a=e.length/t,i=e[0],o=e[e.length-1];for(let d=0;d1&&void 0!==arguments[1]&&arguments[1];const n=N(e.id,"user");!t&&C.users[n]||(C.users[n]=e)}function K(e){e.forEach((e=>{e instanceof g.Api.User&&e.photo?G(e):(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&e.photo&&function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=N(e.id,e instanceof g.Api.Chat?"chat":"channel");t&&C.chats[n]||(C.chats[n]=e)}(e)}))}function z(e){return String.fromCharCode(...e)}function W(e){return L.from(e,"binary")}function j(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 $(e){const t=j(e);return"user"===t?new g.Api.PeerUser({userId:ue(e,"user")}):"channel"===t?new g.Api.PeerChannel({channelId:ue(e,"channel")}):new g.Api.PeerChat({chatId:ue(e,"chat")})}function J(e,t){const n=j(e);return"user"===n?new g.Api.InputPeerUser({userId:ue(e,"user"),accessHash:E()(t)}):"channel"===n?new g.Api.InputPeerChannel({channelId:ue(e,"channel"),accessHash:E()(t)}):new g.Api.InputPeerChat({chatId:ue(e,"chat")})}function Q(e){const t=j(e);let n;var s;if("user"===t){if(n=null===(s=C.users[e])||void 0===s?void 0:s.accessHash,!n)return}else if("channel"===t){var a;if(n=null===(a=C.chats[e])||void 0===a?void 0:a.accessHash,!n)return}return J(e,String(n))}function X(e,t){const n=j(e);return"user"===n?new g.Api.InputUser({userId:ue(e,"user"),accessHash:E()(t)}):"channel"===n?new g.Api.InputChannel({channelId:ue(e,"channel"),accessHash:E()(t)}):ue(e,"chat")}function Z(e,t){return new g.Api.InputStickerSetID({id:E()(e),accessHash:E()(t)})}function Y(e){const t=C.documents[e.id];if(t)return new g.Api.InputDocument(f(t,["id","accessHash","fileReference"]))}function ee(e){const t=Y(e);if(t)return new g.Api.InputMediaDocument({id:t})}function te(){return(0,D.readBigIntFromBuffer)((0,D.generateRandomBytes)(8),!0,!0)}function ne(e,t,n){return new g.Api.Message({id:e,peerId:$(t),fromId:$(t),media:n.media})}function se(e){const{type:t,offset:n,length:s,url:a,userId:i}=e,o=i?C.users[i]:void 0;switch(t){case B.Bold:return new g.Api.MessageEntityBold({offset:n,length:s});case B.Italic:return new g.Api.MessageEntityItalic({offset:n,length:s});case B.Underline:return new g.Api.MessageEntityUnderline({offset:n,length:s});case B.Strike:return new g.Api.MessageEntityStrike({offset:n,length:s});case B.Code:return new g.Api.MessageEntityCode({offset:n,length:s});case B.Pre:return new g.Api.MessageEntityPre({offset:n,length:s,language:""});case B.Blockquote:return new g.Api.MessageEntityBlockquote({offset:n,length:s});case B.TextUrl:return new g.Api.MessageEntityTextUrl({offset:n,length:s,url:a});case B.Url:return new g.Api.MessageEntityUrl({offset:n,length:s});case B.Hashtag:return new g.Api.MessageEntityHashtag({offset:n,length:s});case B.MentionName:return new g.Api.InputMessageEntityMentionName({offset:n,length:s,userId:new g.Api.InputUser({userId:E()(i),accessHash:o.accessHash})});case B.Spoiler:return new g.Api.MessageEntitySpoiler({offset:n,length:s});default:return new g.Api.MessageEntityUnknown({offset:n,length:s})}}function ae(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 ie(e){let{phone:t,firstName:n,lastName:s}=e;return new g.Api.InputPhoneContact({clientId:E()(1),phone:t,firstName:n,lastName:s})}function oe(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return new g.Api.ChatBannedRights({...e,untilDate:t})}function re(e){return new g.Api.ChatAdminRights(e)}function ce(e){const{shippingAddress:t}=e;return new g.Api.PaymentRequestedInfo({...e,shippingAddress:t?new g.Api.PostAddress(t):void 0})}function le(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"illegalDrugs":return new g.Api.InputReportReasonIllegalDrugs;case"personalDetails":return new g.Api.InputReportReasonPersonalDetails;case"other":return new g.Api.InputReportReasonOther}}function ue(e,t){return"number"==typeof e?E()(Math.abs(e)):"user"===t?E()(e):E()(e.slice(1))}function ge(e){return new g.Api.InputGroupCall({id:E()(e.id),accessHash:E()(e.accessHash)})}const pe="temp";let fe,he=1e9;function me(e){const{fromId:t,message:n,entities:s,startParam:a,channelPost:i,chatInvite:o,chatInviteHash:r,randomId:c}=e,l=t?F(t):void 0,d=o?o instanceof g.Api.ChatInvite?o.title:o.chat instanceof g.Api.ChatEmpty?void 0:o.chat.title:void 0;return{randomId:z(c),isBot:!!t&&x(t),text:Ae(n,s),expiresAt:Math.round(Date.now()/1e3)+3e5,...l&&{chatId:l},...r&&{chatInviteHash:r},...o&&{chatInviteTitle:d},...a&&{startParam:a},...i&&{channelPostId:i}}}function _e(e){const t=q(e);if(t&&(e instanceof g.Api.Message||e instanceof g.Api.MessageService))return ye(t,e)}function ye(e,t){const n=t.fromId?F(t.fromId):void 0,s=t.peerId?F(t.peerId):void 0,a=!n&&e===fe,i=t.out&&!t.post||a&&!t.fwdFrom,o=Ce(t),r=t.action&&function(e,t,n,s,a){if(e instanceof g.Api.MessageActionEmpty)return;let i,o,r,c;const l=[];let d,u="other";const p="users"in e?e.users&&e.users.map((e=>N(e,"user"))):"userId"in e&&[N(e.userId,"user")]||[];let f;if(e instanceof g.Api.MessageActionChatCreate)c="Notification.CreatedChatWithTitle",l.push("%action_origin%",e.title),u="chatCreate";else if(e instanceof g.Api.MessageActionChatEditTitle)s?(c="Channel.MessageTitleUpdated",l.push(e.title)):(c="Notification.ChangedGroupName",l.push("%action_origin%",e.title));else if(e instanceof g.Api.MessageActionChatEditPhoto)s?c="Channel.MessagePhotoUpdated":(c="Notification.ChangedGroupPhoto",l.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",l.push("%target_user%")):(c="Notification.Invited",l.push("%action_origin%","%target_user%"));else if(e instanceof g.Api.MessageActionChatDeleteUser)!t||p.includes(t)?(c="Notification.LeftChat",l.push("%target_user%")):(c="Notification.Kicked",l.push("%action_origin%","%target_user%"));else if(e instanceof g.Api.MessageActionChatJoinedByLink)c="Notification.JoinedGroupByLink",l.push("%action_origin%");else if(e instanceof g.Api.MessageActionChannelCreate)c="Notification.CreatedChannel";else if(e instanceof g.Api.MessageActionChatMigrateTo)f=F(e),c="Migrated to %target_chat%",l.push("%target_chat%");else if(e instanceof g.Api.MessageActionChannelMigrateFrom)f=F(e),c="Migrated from %target_chat%",l.push("%target_chat%");else if(e instanceof g.Api.MessageActionPinMessage)c="Chat.Service.Group.UpdatedPinnedMessage1",l.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);l.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()},l.push("%action_origin%","%target_user%");else if(e instanceof g.Api.MessageActionContactSignUp)c="Notification.Joined",l.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),l.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",l.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",l.push(e.domain)):e instanceof g.Api.MessageActionCustomAction?c=e.message:e instanceof g.Api.MessageActionChatJoinedByRequest?(c="ChatService.UserJoinedGroupByRequest",l.push("%action_origin%")):c="ChatList.UnsupportedMessage";return"photo"in e&&e.photo instanceof g.Api.Photo&&(H(e.photo),d=v(e.photo)),{text:c,type:u,targetUserIds:p,targetChatId:f,photo:d,amount:o,currency:r,translationValues:l,call:i}}(t.action,n,s,Boolean(t.post),i);r&&(o.action=r);const{replyToMsgId:c,replyToTopId:l,replyToPeerId:d}=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((e=>{let{buttons:n}=e;return n.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=z(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){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=e.savedFromPeer&&F(e.savedFromPeer),s=e.fromId&&F(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),C=Boolean(I)&&!(o.document||o.audio||o.sticker),A=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&&fe||e,views:t.views,isFromScheduled:t.fromScheduled,reactions:t.reactions&&be(t.reactions),...c&&{replyToMessageId:c},...d&&{replyToChatId:F(d)},...l&&{replyToTopMessageId:l},..._&&{forwardInfo:_},...u&&{isEdited:u},...t.editDate&&{editDate:t.editDate},...b&&{isMediaUnread:b},...t.mentioned&&b&&{hasUnreadMention:!0},...t.mentioned&&{isMentioned:!0},...I&&{groupedId:I,isInAlbum:C},inlineButtons:p,...f&&{keyboardButtons:f,keyboardPlaceholder:h,isKeyboardSingleUse:m},...A&&{shouldHideKeyboardButtons:A},...t.viaBotId&&{viaBotId:N(t.viaBotId,"user")},...(null==y?void 0:y.comments)&&{threadInfo:Ne(y,t.id,e)},...w&&{adminTitle:w},...t.noforwards&&{isProtected:!0}}}function be(e){const{recentReactions:t,results:n,canSeeList:s}=e;return{canSeeList:s,results:n.map(we),recentReactions:null==t?void 0:t.map(ve)}}function we(e){const{chosen:t,count:n,reaction:s}=e;return{isChosen:t,count:n,reaction:s}}function ve(e){const{peerId:t,reaction:n}=e;return{userId:F(t),reaction:n}}function Ie(e){const{selectAnimation:t,staticIcon:n,reaction:s,title:a,inactive:i,aroundAnimation:o,centerIcon:r}=e;return{selectAnimation:ke(t),staticIcon:ke(n),aroundAnimation:o?ke(o):void 0,centerIcon:r?ke(r):void 0,reaction:s,title:a,isInactive:i}}function Ce(e){var t;let n={};return e.media&&(n={...Pe(e.media)}),!e.message||n.sticker||n.poll||n.contact||null!==(t=n.video)&&void 0!==t&&t.isRound||(n={...n,text:Ae(e.message,e.entities)}),n}function Ae(e,t){return{text:e,...t&&{entities:t.map(Ve)}}}function Se(e){if(e instanceof g.Api.DraftMessageEmpty)return;const{message:t,entities:n,replyToMsgId:s,date:a}=e;return{formattedText:t?Ae(t,n):void 0,replyingToId:s,date:a}}function Pe(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 P(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 v(e.photo)}(e);if(n)return{photo:n};const s=function(e){if(e instanceof g.Api.MessageMediaDocument&&e.document instanceof g.Api.Document&&e.document.mimeType.startsWith("video"))return Me(e.document)}(e);if(s)return{video:s};const a=function(e){if(!(e instanceof g.Api.MessageMediaDocument&&e.document&&e.document instanceof g.Api.Document))return;const t=e.document.attributes.find((e=>e instanceof g.Api.DocumentAttributeAudio));if(!t||t.voice)return;const n=e.document.thumbs&&e.document.thumbs.filter((e=>e instanceof g.Api.PhotoSize)).map((e=>I(e)));return{id:String(e.document.id),fileName:Be(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 ke(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:N(a,"user")}}(e);if(r)return{contact:r};const c=function(e){if(e instanceof g.Api.MessageMediaPoll)return Ue(e.poll,e.results)}(e);if(c)return{poll:c};const l=De(e);if(l)return{webPage:l};const d=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);if(d)return{invoice:d};const u=function(e){return e instanceof g.Api.MessageMediaGeo?function(e){const t=Re(e.geo);return t&&{type:"geo",geo:t}}(e):e instanceof g.Api.MessageMediaVenue?function(e){const{geo:t,title:n,provider:s,address:a,venueId:i,venueType:o}=e,r=Re(t);return r&&{type:"venue",geo:r,title:n,provider:s,address:a,venueId:i,venueType:o}}(e):e instanceof g.Api.MessageMediaGeoLive?function(e){const{geo:t,period:n,heading:s}=e,a=Re(t);return a&&{type:"geoLive",geo:a,period:n,heading:s}}(e):void 0}(e);return u?{location:u}:void 0}function Me(e){if(e instanceof g.Api.DocumentEmpty)return;const{id:t,mimeType:n,thumbs:s,size:a,attributes:i}=e;if("video/webm"===n&&!self.isWebmSupported)return;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:l,h:d,supportsStreaming:u=!1,roundMessage:p=!1}=o;return{id:String(t),mimeType:n,duration:c,fileName:Be(e,"video"),width:l,height:d,supportsStreaming:u,isRound:p,isGif:Boolean(r),thumbnail:w(s),size:a}}function ke(e){if(!(e instanceof g.Api.Document))return;const{id:t,size:n,mimeType:s,date:a,thumbs:i,attributes:o}=e,l=i&&w(i);let d,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)){d="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)&&(d="video");return{id:String(t),size:n,mimeType:s,timestamp:a,fileName:Be(e),thumbnail:l,mediaType:d,mediaSize:u}}function Re(e){if(e instanceof g.Api.GeoPointEmpty)return;const{long:t,lat:n,accuracyRadius:s,accessHash:a}=e;return{long:t,lat:n,accessHash:a.toString(),accuracyRadius:s}}function Ue(e,t){const{id:n,answers:s}=e,a=s.map((e=>({text:e.text,option:z(e.option)})));return{id:String(n),summary:{isPublic:e.publicVoters,...f(e,["closed","multipleChoice","quiz","question","closePeriod","closeDate"]),answers:a},results:Ee(t)}}function Ee(e){const{results:t,totalVoters:n,recentVoters:s,solution:a,solutionEntities:i}=e,o=t&&t.map((e=>{let{option:t,chosen:n,correct:s,voters:a}=e;return{isChosen:n,isCorrect:s,option:z(t),votersCount:a}}));return{totalVoters:n,recentVoterIds:null==s?void 0:s.map((e=>N(e,"user"))),results:o,solution:a,...i&&{solutionEntities:i.map(Ve)}}}function De(e){if(!(e instanceof g.Api.MessageMediaWebPage&&e.webpage instanceof g.Api.WebPage))return;const{id:t,photo:n,document:s}=e.webpage;let a;return s instanceof g.Api.Document&&s.mimeType.startsWith("video/")&&(a=Me(s)),{id:Number(t),...f(e.webpage,["url","displayUrl","type","siteName","title","description","duration"]),photo:n instanceof g.Api.Photo?v(n):void 0,document:!a&&s?ke(s):void 0,video:a}}function Be(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"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 Te(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:pe,sizes:[],thumbnail:{width:o,height:r,dataUri:""},blobUrl:n}}:{video:{id:pe,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}=R(n,63);return{voice:{id:pe,duration:t,waveform:s}}}return a.startsWith("audio/")?{audio:{id:pe,mimeType:a,fileName:t,size:i,duration:200}}:{document:{mimeType:a,fileName:t,size:i,...s&&{previewBlobUrl:s}}}}function xe(e,t){return{poll:{id:String(t),summary:f(e.summary,["question","answers"]),results:{}}}}function Ve(e){const{className:t,offset:n,length:s}=e;return{type:t,offset:n,length:s,...e instanceof g.Api.MessageEntityMentionName&&{userId:N(e.userId,"user")},..."url"in e&&{url:e.url}}}function Ne(e,t,n){const{channelId:s,replies:a,maxId:i,readMaxId:o,recentRepliers:r}=e;if(!s)return;const c=N(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(F)}}:void 0}const Fe=e=>Math.floor(Date.now()/1e3)+e;function Le(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=Boolean("min"in e&&e.min),s="accessHash"in e&&String(e.accessHash),a="photo"in e&&e.photo&&Je(e.photo),i=Boolean("signatures"in e&&e.signatures),o=Boolean("hasLink"in e&&e.hasLink);return{isMin:n,hasPrivateLink:o,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},...Oe(e),..."creator"in e&&{isCreator:e.creator},...He(e),...Ge(e)}}function qe(e,t,n){const{peer:s,folderId:a,unreadMark:i,unreadCount:o,unreadMentionsCount:r,notifySettings:{silent:c,muteUntil:l},readOutboxMaxId:d,readInboxMaxId:u,draft:p}=e,f=c||"number"==typeof l&&Fe(n){let{platform:t}=e;return"all"===t}));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 Ge(e){return e instanceof g.Api.Chat&&e.migratedTo&&!(e.migratedTo instanceof g.Api.InputChannelEmpty)?{migratedTo:{chatId:F(e.migratedTo),...e.migratedTo instanceof g.Api.InputChannel&&{accessHash:String(e.migratedTo.accessHash)}}}:{}}function Ke(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];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:N(e.id,e instanceof g.Api.User?"user":"chat"),type:ze(e),title:e instanceof g.Api.User?$e(e):e.title,...Le(e,t)}}function ze(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 We(e){return x(e)?`user${e.userId}`:V(e)?`chat${e.chatId}`:`chat${e.channelId}`}function je(e,t){return x(e)?$e(t):t.title}function $e(e){return e.firstName?`${e.firstName}${e.lastName?` ${e.lastName}`:""}`:e.lastName||void 0}function Je(e){if("photoId"in e)return String(e.photoId)}function Qe(e){return{userId:e instanceof g.Api.ChannelParticipantBanned||e instanceof g.Api.ChannelParticipantLeft?F(e.peer):N(e.userId,"user"),inviterId:"inviterId"in e?N(e.inviterId,"user"):void 0,joinedDate:"date"in e?e.date:void 0,kickedByUserId:"kickedBy"in e?N(e.kickedBy,"user"):void 0,promotedByUserId:"promotedBy"in e?N(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 Xe(e){return e instanceof g.Api.ChatParticipants||e instanceof g.Api.channels.ChannelParticipants?e.participants.map(Qe).filter(Boolean):void 0}function Ze(e,t){let n,s="";if(!(e.action instanceof g.Api.SendMessageCancelAction)){if(e.action instanceof g.Api.SendMessageTypingAction)s="lng_user_typing";else if(e.action instanceof g.Api.SendMessageRecordVideoAction)s="lng_send_action_record_video";else if(e.action instanceof g.Api.SendMessageUploadVideoAction)s="lng_send_action_upload_video";else if(e.action instanceof g.Api.SendMessageRecordAudioAction)s="lng_send_action_record_audio";else if(e.action instanceof g.Api.SendMessageUploadAudioAction)s="lng_send_action_upload_audio";else if(e.action instanceof g.Api.SendMessageUploadPhotoAction)s="lng_send_action_upload_photo";else if(e.action instanceof g.Api.SendMessageUploadDocumentAction)s="lng_send_action_upload_file";else if(e.action instanceof g.Api.SendMessageGeoLocationAction)s="selecting a location to share";else if(e.action instanceof g.Api.SendMessageChooseContactAction)s="selecting a contact to share";else if(e.action instanceof g.Api.SendMessageGamePlayAction)s="lng_playing_game";else if(e.action instanceof g.Api.SendMessageRecordRoundAction)s="lng_send_action_record_round";else if(e.action instanceof g.Api.SendMessageUploadRoundAction)s="lng_send_action_upload_round";else if(e.action instanceof g.Api.SendMessageChooseStickerAction)s="lng_send_action_choose_sticker";else{if(e.action instanceof g.Api.SpeakingInGroupCallAction)return;if(e.action instanceof g.Api.SendMessageEmojiInteractionSeen)s="lng_user_action_watching_animations",n=e.action.emoticon;else if(e.action instanceof g.Api.SendMessageEmojiInteraction)return}return{action:s,...n&&{emoji:n},...!(e instanceof g.Api.UpdateUserTyping)&&{userId:F(e.fromId)},timestamp:Date.now()+1e3*t}}}function Ye(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(F).filter(Boolean),includedChatIds:e.includePeers.map(F).filter(Boolean),excludedChatIds:e.excludePeers.map(F).filter(Boolean)};var t,n}function et(e){let{filter:t,description:n}=e;return{...Ye(t),description:n}}function tt(e){return e.reduce(((e,t)=>{const n=N(t.userId,"user");return e.concat(t.commands.map((e=>({botId:n,..._(e)}))))}),[])}function nt(e){const{revoked:t,date:n,expireDate:s,link:a,permanent:i,startDate:o,usage:r,usageLimit:c,requested:l,requestNeeded:d,title:u,adminId:g}=e;return{isRevoked:t,date:n,expireDate:s,link:a,isPermanent:i,startDate:o,usage:r,usageLimit:c,isRequestNeeded:d,requested:l,title:u,adminId:N(g,"user")}}function st(e){let{autoarchived:t,reportSpam:n,addContact:s,blockContact:a}=e;return{isAutoArchived:Boolean(t),canReportSpam:Boolean(n),canAddContact:Boolean(s),canBlockContact:Boolean(a)}}function at(e){const{fullUser:{about:t,commonChatsCount:n,pinnedMsgId:s,botInfo:a,blocked:i},users:o}=e,r=it(o[0]);return{...r,fullInfo:{bio:t,commonChatsCount:n,pinnedMessageId:s,isBlocked:Boolean(i),...a&&{botDescription:a.description},...a&&a.commands.length&&{botCommands:rt(r.id,a)}}}}function it(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:N(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 ot(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 rt(e,t){return t.commands.map((t=>{let{command:n,description:s}=t;return{botId:e,command:n,description:s}}))}function ct(e){const t={},n=[];return e.forEach((e=>{const s=it(e);s&&(n.push(s),"status"in e&&(t[s.id]=ot(e.status)))})),{users:n,userStatusesById:t}}function lt(e){if(e instanceof g.Api.WallPaperNoFile)return;const{slug:t}=e,n=ke(e.document);return n?{slug:t,document:n}:void 0}function dt(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 ut(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=>N(e,"user"))):e instanceof g.Api.PrivacyValueDisallowUsers?a=e.users.map((e=>N(e,"user"))):e instanceof g.Api.PrivacyValueAllowChatParticipants?s=e.chats.map((e=>N(e,"chat"))):e instanceof g.Api.PrivacyValueDisallowChatParticipants&&(i=e.chats.map((e=>N(e,"chat"))))})),t||(t="nobody"),{visibility:t,allowUserIds:n||[],allowChatIds:s||[],blockUserIds:a||[],blockChatIds:i||[]}}function gt(e,t,n){const{silent:s,muteUntil:a,showPreviews:i,sound:o}=e;return{chatId:F(t),isMuted:s||"number"==typeof a&&Fe(n)(e[t.key]=ft(t.value),e)),{})}function ht(e){const{self:t,min:n,about:s,date:a,versioned:i,canSelfUnmute:o,justJoined:r,left:c,muted:l,mutedByYou:d,source:u,volume:g,volumeByAdmin:p,videoJoined:f,peer:h,video:m,presentation:_,raiseHandRating:y}=e;return{isSelf:t,isMin:n,canSelfUnmute:o,isLeft:c,isMuted:l,isMutedByMe:d,hasJustJoined:r,isVolumeByAdmin:p,isVersioned:i,isVideoJoined:f,about:s,source:u,raiseHandRating:null==y?void 0:y.toString(),volume:g,date:new Date(a),isUser:x(h),id:F(h),video:m?mt(m):void 0,presentation:_?mt(_):void 0}}function mt(e){const{audioSource:t,endpoint:n,paused:s,sourceGroups:a}=e;return{audioSource:t,endpoint:n,isPaused:s,sourceGroups:a.map(_t)}}function _t(e){return{semantics:e.semantics,sources:e.sources}}function yt(e){const{id:t,accessHash:n}=e;if(e instanceof g.Api.GroupCallDiscarded)return{connectionState:"discarded",id:t.toString(),accessHash:n.toString(),participantsCount:0,version:0,participants:{}};const{version:s,participantsCount:a,streamDcId:i,scheduleDate:o,canChangeJoinMuted:r,joinMuted:c,canStartVideo:l,scheduleStartSubscribed:d}=e;return{connectionState:"disconnected",isLoaded:!0,id:t.toString(),accessHash:n.toString(),version:s,participantsCount:a,streamDcId:i,scheduleDate:o,canChangeJoinMuted:r,joinMuted:c,canStartVideo:l,scheduleStartSubscribed:d,participants:{}}}let bt;const wt=new Set;let vt=0,It=!1;function Ct(e){e.filter((e=>e instanceof g.Api.User)).map(it).forEach((e=>{e&&bt({"@type":"updateUser",id:e.id,user:e})})),e.filter((e=>e instanceof g.Api.Chat||e instanceof g.Api.Channel)).map((e=>Ke(e))).forEach((e=>{e&&bt({"@type":"updateChat",id:e.id,chat:e})}))}function At(e,t){if(e instanceof g.connection.UpdateServerTimeOffset)vt=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"}bt({"@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=ye(N((i=e).chatId,"chat"),{...i,fromId:$(N(i.fromId,"user"))});else if(e instanceof g.Api.UpdateShortMessage)t=function(e){return ye(N(e.userId,"user"),{...e,fromId:$(e.out?fe:N(e.userId,"user"))})}(e);else{var n;if(e.message instanceof g.Api.MessageEmpty)return;e.message instanceof g.Api.Message&&ae(e.message)&&O(e.message),t=_e(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 a=e._entities;if(a&&(K(a),Ct(a)),e instanceof g.Api.UpdateNewScheduledMessage?bt({"@type":wt.has(t.id)?"updateScheduledMessage":"newScheduledMessage",id:t.id,chatId:t.chatId,message:t}):bt({"@type":wt.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.MessageActionPaymentSent)bt({"@type":"updatePaymentStateCompleted"});else if(n instanceof g.Api.MessageActionChatEditTitle)bt({"@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=Je(s),i=q(e.message);C.chats[i]&&(C.chats[i].photo=s),H(n.photo),a&&bt({"@type":"updateChat",id:t.chatId,chat:{avatarHash:a},...n.photo instanceof g.Api.Photo&&{newProfilePhoto:v(n.photo)}})}else if(n instanceof g.Api.MessageActionChatDeletePhoto){const n=q(e.message);C.chats[n]&&(C.chats[n].photo=new g.Api.ChatPhotoEmpty),bt({"@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&&Boolean(e.self)&&e.id===n.userId))&&(bt({"@type":"updateChat",id:t.chatId,chat:{isRestricted:!0}}),bt({"@type":"updateChatLeave",id:t.chatId})):n instanceof g.Api.MessageActionChatAddUser?e._entities&&e._entities.some((e=>e instanceof g.Api.User&&Boolean(e.self)&&n.users.includes(e.id)))&&bt({"@type":"updateChatJoin",id:t.chatId}):n instanceof g.Api.MessageActionGroupCall&&!n.duration&&n.call&&bt({"@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&&ae(e.message)&&O(e.message);const t=_e(e.message);bt({"@type":"updateMessage",id:t.id,chatId:t.chatId,message:t})}else if(e instanceof g.Api.UpdateMessageReactions)bt({"@type":"updateMessageReactions",id:e.msgId,chatId:F(e.peer),reactions:be(e.reactions)});else if(e instanceof g.Api.UpdateDeleteMessages)bt({"@type":"deleteMessages",ids:e.messages});else if(e instanceof g.Api.UpdateDeleteScheduledMessages)bt({"@type":"deleteScheduledMessages",ids:e.messages,chatId:F(e.peer)});else if(e instanceof g.Api.UpdateDeleteChannelMessages){const t=N(e.channelId,"channel"),n=e.messages,s=n.filter((e=>C.messages[`${t}-${e}`])),a=n.filter((e=>!C.messages[`${t}-${e}`])),i=n.map((e=>{const n=C.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&&bt({"@type":"deleteMessages",ids:s,chatId:t}),i.length&&bt({"@type":"deleteProfilePhotos",ids:i,chatId:t}),a.length&&setTimeout((()=>{bt({"@type":"deleteMessages",ids:a,chatId:t})}),1e3)}else if(e instanceof g.Api.UpdateServiceNotification)if(e.popup)bt({"@type":"error",error:{message:e.message}});else{const t=function(e,t){const n=he++,s=Ce(e);return{id:n,chatId:l,date:e.inboxDate||t,content:s,isOutgoing:!1}}(e,Date.now()/1e3+vt);ae(e)&&O(ne(t.id,t.chatId,e)),bt({"@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&&C.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:Ae(s.content.text.text,e.entities)}),e.media&&(a={...a,...Pe(e.media)});const t=ne(e.id,s.chatId,e);ae(t)&&O(t)}wt.add(e.id);const i="date"in e&&1e3*e.datee instanceof g.Api.DialogPeer)).map((e=>F(e.peer))):[];bt({"@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;bt({"@type":"updateChatListType",id:F(n),folderId:t})}));else if(e instanceof g.Api.UpdateDialogFilter){const{id:t,filter:n}=e,s=n?Ye(n):void 0;bt({"@type":"updateChatFolder",id:t,folder:s})}else if(e instanceof g.Api.UpdateDialogFilterOrder)bt({"@type":"updateChatFoldersOrder",orderedIds:e.order});else if(e instanceof g.Api.UpdateChatParticipants){const t=Xe(e.participants);bt({"@type":"updateChatMembers",id:N(e.participants.chatId,"chat"),replacedMembers:t})}else if(e instanceof g.Api.UpdateChatParticipantAdd){const t=Qe(f(e,["userId","inviterId","date"]));bt({"@type":"updateChatMembers",id:N(e.chatId,"chat"),addedMember:t})}else if(e instanceof g.Api.UpdateChatParticipantDelete)bt({"@type":"updateChatMembers",id:N(e.chatId,"chat"),deletedMemberId:N(e.userId,"user")});else if(e instanceof g.Api.UpdatePinnedMessages||e instanceof g.Api.UpdatePinnedChannelMessages){const t=e instanceof g.Api.UpdatePinnedMessages?F(e.peer):N(e.channelId,"channel");bt({"@type":"updatePinnedIds",chatId:t,messageIds:e.messages,isPinned:e.pinned})}else if(e instanceof g.Api.UpdateNotifySettings&&e.peer instanceof g.Api.NotifyPeer)bt({"@type":"updateNotifyExceptions",...gt(e.notifySettings,e.peer.peer,vt)});else if(e instanceof g.Api.UpdateUserTyping||e instanceof g.Api.UpdateChatUserTyping){const t=e instanceof g.Api.UpdateUserTyping?N(e.userId,"user"):N(e.chatId,"chat");e.action instanceof g.Api.SendMessageEmojiInteraction?bt({"@type":"updateStartEmojiInteraction",id:t,emoji:e.action.emoticon,messageId:e.action.msgId,interaction:(a=JSON.parse(e.action.interaction.data),{timestamps:a.a.map((e=>e.t))})}):bt({"@type":"updateChatTypingStatus",id:t,typingStatus:Ze(e,vt)})}else if(e instanceof g.Api.UpdateChannelUserTyping){const t=N(e.channelId,"channel");bt({"@type":"updateChatTypingStatus",id:t,typingStatus:Ze(e,vt)})}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(It)return void(It=!1);t instanceof g.Api.messages.ToggleNoForwards&&(It=!0,setTimeout((()=>{It=!1}),2e3));const n=Ke(s);n&&(bt({"@type":"updateChat",id:n.id,chat:n}),bt({"@type":n.isNotJoined?"updateChatLeave":"updateChatJoin",id:N(e.channelId,"channel")}))}else if(s instanceof g.Api.ChannelForbidden){const t=N(e.channelId,"channel");bt({"@type":"updateChat",id:t,chat:{isRestricted:!0}}),bt({"@type":"updateChatLeave",id:t})}else 0===n.length&&bt({"@type":"resetMessages",id:N(e.channelId,"channel")})}else if(e instanceof g.Api.UpdateDialogUnreadMark&&e.peer instanceof g.Api.DialogPeer)bt({"@type":"updateChat",id:F(e.peer.peer),chat:{hasUnreadMark:e.unread}});else if(e instanceof g.Api.UpdateChatDefaultBannedRights)bt({"@type":"updateChat",id:F(e.peer),chat:{defaultBannedRights:_(e.defaultBannedRights)}});else if(e instanceof g.Api.UpdateUserStatus)bt({"@type":"updateUserStatus",userId:N(e.userId,"user"),status:ot(e.status)});else if(e instanceof g.Api.UpdateUserName){const t=N(e.userId,"user"),n=C.users[t],s=null!=n&&n.mutualContact&&!n.self?f(e,["username"]):f(e,["firstName","lastName","username"]);bt({"@type":"updateUser",id:t,user:s})}else if(e instanceof g.Api.UpdateUserPhoto){const{userId:t,photo:n}=e,s=N(t,"user"),a=Je(n);C.users[s]&&(C.users[s].photo=n),bt({"@type":"updateUser",id:s,user:{avatarHash:a}})}else if(e instanceof g.Api.UpdateUserPhone){const{userId:t,phone:n}=e;bt({"@type":"updateUser",id:N(t,"user"),user:{phoneNumber:n}})}else if(e instanceof g.Api.UpdatePeerSettings){const{_entities:t,settings:n}=e;if(!t)return;null!=t&&t.length&&(t.filter((e=>e instanceof g.Api.User&&!e.contact)).forEach((e=>{bt({"@type":"deleteContact",id:N(e.id,"user")})})),t.filter((e=>e instanceof g.Api.User&&e.contact)).map(it).forEach((e=>{e&&bt({"@type":"updateUser",id:e.id,user:{...e,...n&&{settings:st(n)}}})})))}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;bt({"@type":"updateNotifySettings",peerType:i,isSilent:Boolean(n||"number"==typeof s&&Date.now()+1e3*vt<1e3*s),shouldShowPreviews:Boolean(t)})}else if(e instanceof g.Api.UpdatePeerBlocked)bt({"@type":"updatePeerBlocked",id:F(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&&bt({"@type":"updatePrivacy",key:t,rules:ut(e.rules)})}else if(e instanceof g.Api.UpdateDraftMessage)bt({"@type":"draftMessage",chatId:F(e.peer),...Se(e.draft)});else if(e instanceof g.Api.UpdateContactsReset)bt({"@type":"updateResetContactList"});else if(e instanceof g.Api.UpdateFavedStickers)bt({"@type":"updateFavoriteStickers"});else if(e instanceof g.Api.UpdateGroupCall)bt({"@type":"updateGroupCall",call:yt(e.call)});else if(e instanceof g.Api.UpdateGroupCallConnection)bt({"@type":"updateGroupCallConnection",data:JSON.parse(e.params.data),presentation:Boolean(e.presentation)});else if(e instanceof g.Api.UpdateGroupCallParticipants){const t=e._entities;t&&(K(t),Ct(t)),bt({"@type":"updateGroupCallParticipants",groupCallId:(s=e.call,s.id.toString()),participants:e.participants.map(ht)})}else if(e instanceof g.Api.UpdatePendingJoinRequests){const t=e._entities;t&&(K(t),Ct(t)),bt({"@type":"updatePendingJoinRequests",chatId:F(e.peer),recentRequesterIds:e.recentRequesters.map((e=>N(e,"user"))),requestsPending:e.requestsPending})}var s,a,i}const St={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."},Pt={};let Mt;function kt(){return Mt(Tt("authorizationStateWaitPhoneNumber")),new Promise(((e,t)=>{Pt.resolve=e,Pt.reject=t}))}function Rt(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return Mt({...Tt("authorizationStateWaitCode"),isCodeViaApp:e}),new Promise(((e,t)=>{Pt.resolve=e,Pt.reject=t}))}function Ut(e){return Mt({...Tt("authorizationStateWaitPassword"),hint:e}),new Promise((e=>{Pt.resolve=e}))}function Et(){return Mt(Tt("authorizationStateWaitRegistration")),new Promise((e=>{Pt.resolve=e}))}function Dt(e){return Mt({...Tt("authorizationStateWaitQrCode"),qrCode:{token:btoa(String.fromCharCode(...e.token)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),expires:e.expires}}),new Promise(((e,t)=>{Pt.reject=t}))}function Bt(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=St[e.message];t||(t="Unexpected Error"),Mt({"@type":"updateAuthorizationError",message:t})}function Tt(e){return{"@type":"updateAuthorizationState",authorizationState:e}}function xt(e){Pt.resolve&&Pt.resolve(e)}function Vt(e){Pt.resolve&&Pt.resolve(e)}function Nt(e){Pt.resolve&&Pt.resolve(e)}function Ft(e){const{firstName:t,lastName:n}=e;Pt.resolve&&Pt.resolve([t,n])}function Lt(){Pt.reject&&Pt.reject(new Error("RESTART_AUTH"))}function qt(){Pt.reject&&Pt.reject(new Error("RESTART_AUTH_WITH_QR"))}var Ot=n(9832);const Ht=self.caches;let Gt;async function Kt(e,t,n){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(Ht)try{const a=new Request(t.replace(/:/g,"_")),i=await Ht.open(e),o=await i.match(a);if(!o)return;const r=o.headers.get("Content-Type");switch(n){case Gt.Text:return await o.text();case Gt.Blob:{if(t.startsWith("avatar")&&r&&r.startsWith("text"))return;const e=await o.blob(),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 Gt.Json:return await o.json();default:return}}catch(e){return void console.warn(e)}}async function zt(e,t,n){if(Ht)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 Ht.open(e);return await o.put(a,i)}catch(e){return void console.warn(e)}}async function Wt(e){try{if(!Ht)return;return await Ht.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"}(Gt||(Gt={}));const jt=new Set(["msg","sticker","gif","wallpaper","photo","webDocument","document"]);function $t(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"image/jpeg";if(e.length<4)return t;let n=t;const s=e.subarray(0,4).reduce(((e,t)=>e+t.toString(16)),"");switch(s){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}Ot.Logger.setLevel("warn");const Jt={build:e=>e};let Qt,Xt,Zt=!1;async function Yt(){await sn(new g.Api.auth.LogOut),await Xt.destroy()}async function en(){await Xt.disconnect()}function tn(e){Qt({"@type":"updateSession",sessionData:e})}function nn(e){e instanceof g.connection.UpdateConnectionState?Zt=e.state===g.connection.UpdateConnectionState.connected:e instanceof g.Api.UpdatesTooLong?async function(){try{await sn(new g.Api.users.GetFullUser({id:new g.Api.InputUserSelf}),void 0,!0)}catch(e){"AUTH_KEY_UNREGISTERED"===e.message&&Qt({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}}():e instanceof g.connection.UpdateServerTimeOffset&&Qt({"@type":"updateServerTimeOffset",serverTimeOffset:e.timeOffset})}async function sn(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=arguments.length>3&&void 0!==arguments[3]&&arguments[3],a=arguments.length>4?arguments[4]:void 0;if(Zt)try{const n=await Xt.invoke(e,a);return s||an(e,n),t?n&&!0:n}catch(t){if(n)throw t;return void dn(t,e)}}function an(e,t){let n,s;t instanceof g.Api.UpdatesCombined||t instanceof g.Api.Updates?n=t:"object"==typeof t&&"updates"in t&&(t.updates instanceof g.Api.Updates||t.updates instanceof g.Api.UpdatesCombined)?n=t.updates:(t instanceof g.Api.UpdateShortMessage||t instanceof g.Api.UpdateShortChatMessage||t instanceof g.Api.UpdateShort||t instanceof g.Api.UpdateShortSentMessage)&&(s=t),n?(function(e){const t=[...e.users,...e.chats];e.updates.forEach((e=>{t&&(e._entities=t)}))}(n),n.updates.forEach((t=>{At(t,e)}))):s&&At(s,e)}function on(e,t){return async function(e,t,n,a){let{url:i,mediaFormat:o,start:r,end:c,isHtmlAllowed:l}=e;const{data:d,mimeType:u,fullSize:p}=await async function(e,t,n,s,a,i,o,r){const c=e.startsWith("staticMap")?e.match(/(staticMap):([0-9-]+)(\?.+)/):e.startsWith("webDocument")?e.match(/(webDocument):(.+)/):e.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file|document)([-\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 l;const d=c[2],u=c[3]?c[3].replace("?size=",""):void 0;let p;if("staticMap"===c[1]){const e=c[2],n=c[3],s=new URLSearchParams(n),a=s.get("long"),i=s.get("lat"),o=s.get("w"),r=s.get("h"),l=s.get("zoom"),d=s.get("scale"),u=s.get("accuracy_radius");return{mimeType:"image/png",data:await t.downloadStaticMap(e,a,i,o,r,l,d,u)}}switch(l="avatar"===c[1]||"profile"===c[1]?j(d):c[1],l){case"channel":case"chat":p=C.chats[d];break;case"user":p=C.users[d];break;case"msg":p=C.messages[d];break;case"sticker":case"gif":case"wallpaper":case"document":p=C.documents[d];break;case"photo":p=C.photos[d];break;case"stickerSet":p=C.stickerSets[d];break;case"webDocument":p=C.webDocuments[d]}if(p){if(jt.has(l)){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.MessageMediaGeo||e.media instanceof g.Api.MessageMediaVenue||e.media instanceof g.Api.MessageMediaGeoLive?"image/png":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?t?"image/jpeg":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"===l&&u?n="image/webp":"webDocument"===l?n=p.mimeType:(n=p.mimeType,c=p.size),!r&&n&&(n=n.replace(/html/gi,"")),{mimeType:n,data:e,fullSize:c}}if("stickerSet"===l){const e=await t.downloadStickerSetThumb(p);return{mimeType:o===T.Lottie?"application/x-tgsticker":$t(e),data:e}}{const e=await t.downloadProfilePhoto(p,"profile"===c[1]);return{mimeType:$t(e),data:e}}}}(i,t,n,a,r,c,o,l)||{};if(!d)return;const f=await async function(e,t,n){switch(t){case T.BlobUrl:case T.Lottie:return new Blob([e],{type:n});case T.Progressive:return e.buffer}}(d,o,u);if(!f)return;const h=o!==T.Progressive&&(o!==T.BlobUrl||f.size<=524288);return s&&h&&zt(i.startsWith("avatar")?"tt-media-avatars":"tt-media",i,f),{prepared:o===T.Progressive?"":(m=f,m instanceof Blob?URL.createObjectURL(m):m),arrayBuffer:o===T.Progressive?f:void 0,mimeType:u,fullSize:p};var m}(e,Xt,Zt,t)}function rn(e,t){return Xt.uploadFile({file:e,onProgress:t,workers:16})}function cn(e){return Xt.updateTwoFaSettings(e)}async function ln(){const e=await sn(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];C.users[N(t.id,"user")]=t;const n=at(e);var s;s=n.id,fe=s,function(e){Mt({"@type":"updateCurrentUser",currentUser:e})}(n)}function dn(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;Qt({"@type":"error",error:{message:s,isSlowMode:n,hasErrorKey:!0}})}const un=2**31-1;let gn;async function pn(e){let{limit:t,offsetDate:n,archived:s,withPinned:a,serverTimeOffset:i,lastLocalServiceMessage:o}=e;const r=await sn(new g.Api.messages.GetDialogs({offsetPeer:new g.Api.InputPeerEmpty,limit:t,offsetDate:n,folderId:s?1:void 0,...a&&{excludePinned:!0}})),c=a?await sn(new g.Api.messages.GetPinnedDialogs({folderId:s?1:void 0})):void 0;if(!r||r instanceof g.Api.messages.DialogsNotModified)return;c&&ts(c),ts(r);const d=p((c?c.messages:[]).concat(r.messages).map(_e).filter(Boolean),"chatId"),u={...c&&es(c),...es(r)},f=[],h={},m={},_=(c?c.dialogs:[]).concat(r.dialogs),y=[];_.forEach((e=>{if(!(e instanceof g.Api.Dialog)||!s&&1===e.folderId||s&&1!==e.folderId)return;const t=qe(e,u[We(e.peer)],i);if(t.id===l&&o&&(!d[t.id]||o.date>d[t.id].date)?t.lastMessage=o:t.lastMessage=d[t.id],t.isListed=!0,f.push(t),a&&e.pinned&&y.push(t.id),e.draft){const{formattedText:n,replyingToId:s}=Se(e.draft)||{};n&&(h[t.id]=n),s&&(m[t.id]=s)}}));const b=f.map((e=>e.id)),{users:w,userStatusesById:v}=ct(((null==c?void 0:c.users)||[]).concat(r.users));let I;return I=r instanceof g.Api.messages.DialogsSlice?r.count:b.length,{chatIds:b,chats:f,users:w,userStatusesById:v,draftsById:h,replyingToById:m,orderedPinnedIds:a?y:void 0,totalChatCount:I}}function fn(e){const{id:t,accessHash:n,adminRights:s}=e;return X(t,n)instanceof g.Api.InputChannel?async function(e,t,n){var s;const a=await sn(new g.Api.channels.GetFullChannel({channel:X(e,t)}));if(!(a&&a.fullChat instanceof g.Api.ChannelFull))return;const{about:i,onlineCount:o,exportedInvite:r,slowmodeSeconds:c,slowmodeNextSendDate:l,migratedFromChatId:d,migratedFromMaxId:u,canViewParticipants:p,canViewStats:f,linkedChatId:h,hiddenPrehistory:m,call:_,botInfo:y,availableReactions:b,defaultSendAs:w,requestsPending:v,recentRequesters:I,statsDc:C,participantsCount:A}=a.fullChat,S=r instanceof g.Api.ChatInviteExported?r.link:void 0,{members:P,users:M}=p&&await jn(e,t)||{},{members:k,users:R}=p&&n&&await jn(e,t,"kicked")||{},{members:U,users:E}=p&&n&&await jn(e,t,"admin")||{},D=y?tt(y):void 0;if((null==a||null===(s=a.chats)||void 0===s?void 0:s.length)>1){ts(a);const[,e]=a.chats,t=Ke(e,void 0,!0);t&&gn({"@type":"updateChat",id:t.id,chat:t})}return{fullInfo:{about:i,onlineCount:o,inviteLink:S,slowMode:c?{seconds:c,nextSendDate:l}:void 0,migratedFrom:d?{chatId:N(d,"chat"),maxMessageId:u}:void 0,canViewMembers:p,canViewStatistics:f,isPreHistoryHidden:m,members:P,kickedMembers:k,adminMembers:U,groupCallId:_?String(_.id):void 0,linkedChatId:h?N(h,"chat"):void 0,botCommands:D,enabledReactions:b,sendAsId:w?F(w):void 0,requestsPending:v,recentRequesterIds:null==I?void 0:I.map((e=>N(e,"user"))),statisticsDcId:C},users:[...M||[],...R||[],...E||[]],groupCall:_?{chatId:e,isLoaded:!1,id:_.id.toString(),accessHash:null==_?void 0:_.accessHash.toString(),participants:{},version:0,participantsCount:0,connectionState:"disconnected"}:void 0,membersCount:A}}(t,n,s):async function(e){const t=await sn(new g.Api.messages.GetFullChat({chatId:X(e)}));if(!(t&&t.fullChat instanceof g.Api.ChatFull))return;ts(t);const{about:n,participants:s,exportedInvite:a,botInfo:i,call:o,availableReactions:r,recentRequesters:c,requestsPending:l}=t.fullChat,d=Xe(s),u=d?d.filter((e=>{let{isAdmin:t,isOwner:n}=e;return t||n})):void 0;return{fullInfo:{about:n,members:d,adminMembers:u,canViewMembers:!0,botCommands:i?tt(i):void 0,...a&&{inviteLink:a.link},groupCallId:null==o?void 0:o.id.toString(),enabledReactions:r,requestsPending:l,recentRequesterIds:null==c?void 0:c.map((e=>N(e,"user")))},users:t.users.map(it).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,membersCount:null==d?void 0:d.length}}(t)}async function hn(e){const{id:t,accessHash:n}=e,s=await sn(new g.Api.messages.GetPeerSettings({peer:J(t,n)}));if(s)return st(s.settings)}async function mn(e){let{query:t}=e;const n=await sn(new g.Api.contacts.Search({q:t}));if(!n)return;ts(n);const s=n.myResults.map(F),a=n.chats.concat(n.users).map((e=>Ke(e))).filter(Boolean),i=n.users.map(it).filter((e=>Boolean(e)&&!e.isSelf));return{localChats:a.filter((e=>s.includes(e.id))),localUsers:i.filter((e=>s.includes(e.id))),globalChats:a.filter((e=>!s.includes(e.id))),globalUsers:i.filter((e=>!s.includes(e.id)))}}async function _n(e){let t,{type:n,user:s}=e;if("self"===n||"user"===n){const e=await sn(new g.Api.users.GetUsers({id:["user"===n&&s?X(s.id,s.accessHash):new g.Api.InputUserSelf]}));if(!e||!e.length)return;[t]=e}else if("support"===n){const e=await sn(new g.Api.help.GetSupport);if(!e||!e.user)return;t=e.user}const a=Ke(t,"support"===n);if(a)return gn({"@type":"updateChat",id:a.id,chat:a}),{chatId:a.id}}async function yn(e){let{chat:t,serverTimeOffset:n,lastLocalMessage:s,noLastMessage:a}=e;const{id:i,accessHash:o}=t,r=await sn(new g.Api.messages.GetPeerDialogs({peers:[new g.Api.InputDialogPeer({peer:J(i,o)})]}));if(!r)return;const c=r.dialogs[0];if(!(c&&c instanceof g.Api.Dialog))return;const l=es(r)[We(c.peer)];if(!l)return;ts(r);const d=_e(r.messages[0]),u=s&&(!d||s.date>d.date)?s:d;gn({"@type":"updateChat",id:i,chat:{...qe(c,l,n),...!a&&{lastMessage:u}}})}function bn(e){let{chat:t,text:n,entities:s,replyToMsgId:a}=e;return sn(new g.Api.messages.SaveDraft({peer:J(t.id,t.accessHash),message:n,...s&&{entities:s.map(se)},replyToMsgId:a}))}function wn(e){return sn(new g.Api.messages.SaveDraft({peer:J(e.id,e.accessHash),message:""}))}async function vn(e){let{chat:t,isMuted:n,serverTimeOffset:s}=e;await sn(new g.Api.account.UpdateNotifySettings({peer:new g.Api.InputNotifyPeer({peer:J(t.id,t.accessHash)}),settings:new g.Api.InputPeerNotifySettings({muteUntil:n?un:0})})),gn({"@type":"updateNotifyExceptions",chatId:t.id,isMuted:n}),yn({chat:t,serverTimeOffset:s,noLastMessage:!0})}async function In(e){let{title:t,about:n="",users:s}=e,a=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=await sn(new g.Api.channels.CreateChannel({broadcast:!0,title:t,about:n}));if(!(i instanceof g.Api.Updates))return;const o=i.chats[0];if(!(o&&o instanceof g.Api.Channel))return;const r=Ke(o);if(null!=s&&s.length)try{await sn(new g.Api.channels.InviteToChannel({channel:X(r.id,r.accessHash),users:s.map((e=>{let{id:t,accessHash:n}=e;return X(t,n)}))}),void 0,a)}catch(e){}return r}function Cn(e){let{channelId:t,accessHash:n}=e;return sn(new g.Api.channels.JoinChannel({channel:X(t,n)}),!0)}function An(e){let{chat:t,user:n}=e;if("chatTypeBasicGroup"===t.type)return sn(new g.Api.messages.DeleteChatUser({chatId:X(t.id,t.accessHash),userId:X(n.id,n.accessHash)}),!0)}function Sn(e){let{chatId:t}=e;return sn(new g.Api.messages.DeleteChat({chatId:X(t)}),!0)}function Pn(e){let{channelId:t,accessHash:n}=e;return sn(new g.Api.channels.LeaveChannel({channel:X(t,n)}),!0)}function Mn(e){let{channelId:t,accessHash:n}=e;return sn(new g.Api.channels.DeleteChannel({channel:X(t,n)}),!0)}async function kn(e){let{title:t,users:n}=e;const s=await sn(new g.Api.messages.CreateChat({title:t,users:n.map((e=>{let{id:t,accessHash:n}=e;return X(t,n)}))}),void 0,!0);if(!(s instanceof g.Api.Updates))return;const a=s.chats[0];return a&&a instanceof g.Api.Chat?Ke(a):void 0}async function Rn(e){let{chatId:t,accessHash:n,photo:s}=e;const a=await rn(s),i=X(t,n);return sn(i instanceof g.Api.InputChannel?new g.Api.channels.EditPhoto({channel:i,photo:new g.Api.InputChatUploadedPhoto({file:a})}):new g.Api.messages.EditChatPhoto({chatId:i,photo:new g.Api.InputChatUploadedPhoto({file:a})}),!0)}async function Un(e){let{chat:t,shouldBePinned:n}=e;const{id:s,accessHash:a}=t;await sn(new g.Api.messages.ToggleDialogPin({peer:new g.Api.InputDialogPeer({peer:J(s,a)}),pinned:n||void 0}))&&gn({"@type":"updateChatPinned",id:t.id,isPinned:n})}function En(e){let{chat:t,folderId:n}=e;const{id:s,accessHash:a}=t;return sn(new g.Api.folders.EditPeerFolders({folderPeers:[new g.Api.InputFolderPeer({peer:J(s,a),folderId:n})]}),!0)}async function Dn(){const e=await sn(new g.Api.messages.GetDialogFilters);if(e)return{byId:p(e.map(Ye),"id"),orderedIds:e.map((e=>{let{id:t}=e;return t}))}}async function Bn(){const e=await sn(new g.Api.messages.GetSuggestedDialogFilters);if(e)return e.map(et)}async function Tn(e){let{id:t,folderUpdate:n}=e;const s=function(e){const{emoticon:t,contacts:n,nonContacts:s,groups:a,channels:i,bots:o,excludeArchived:r,excludeMuted:c,excludeRead:l,pinnedChatIds:d,includedChatIds:u,excludedChatIds:p}=e,f=d?d.map(Q).filter(Boolean):[],h=u?u.map(Q).filter(Boolean):[],m=p?p.map(Q).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:l||void 0,broadcasts:i||void 0,pinnedPeers:f,includePeers:h,excludePeers:m})}(n);await sn(new g.Api.messages.UpdateDialogFilter({id:t,filter:s}))&&gn({"@type":"updateChatFolder",id:t,folder:n})}async function xn(e){const t=await sn(new g.Api.messages.UpdateDialogFilter({id:e,filter:void 0})),n=await Bn();t&&gn({"@type":"updateChatFolder",id:e,folder:void 0}),n&&gn({"@type":"updateRecommendedChatFolders",folders:n})}async function Vn(e){let{chat:t,hasUnreadMark:n}=e;const{id:s,accessHash:a}=t;await sn(new g.Api.messages.MarkDialogUnread({peer:new g.Api.InputDialogPeer({peer:J(s,a)}),unread:n||void 0}))&&gn({"@type":"updateChat",id:t.id,chat:{hasUnreadMark:n}})}async function Nn(e){return Ln(await sn(new g.Api.contacts.ResolvePhone({phone:e})))}async function Fn(e){return Ln(await sn(new g.Api.contacts.ResolveUsername({username:e})))}function Ln(e){if(!e)return;const{users:t,chats:n}=e,s=n.length?Ke(n[0]):Ke(t[0]);return s?(ts(e),s):void 0}function qn(e){let{chat:t,isEnabled:n}=e;const{id:s,accessHash:a}=t,i=X(s,a);return sn(new g.Api.channels.TogglePreHistoryHidden({channel:i,enabled:n}),!0)}function On(e){let{chat:t,bannedRights:n}=e;const{id:s,accessHash:a}=t,i=J(s,a);return sn(new g.Api.messages.EditChatDefaultBannedRights({peer:i,bannedRights:oe(n)}),!0)}function Hn(e){let{chat:t,user:n,bannedRights:s,untilDate:a}=e;const i=X(t.id,t.accessHash),o=J(n.id,n.accessHash);return sn(new g.Api.channels.EditBanned({channel:i,participant:o,bannedRights:oe(s,a)}),!0)}function Gn(e){let{chat:t,user:n,adminRights:s,customTitle:a=""}=e;const i=X(t.id,t.accessHash),o=X(n.id,n.accessHash);return sn(new g.Api.channels.EditAdmin({channel:i,userId:o,adminRights:re(s),rank:a}),!0)}async function Kn(e,t){const n=X(e.id,e.accessHash);await sn(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 zn(e,t){await sn(new g.Api.messages.EditChatAbout({peer:J(e.id,e.accessHash),about:t}))&&gn({"@type":"updateChatFullInfo",id:e.id,fullInfo:{about:t}})}function Wn(e){let{chat:t,isEnabled:n}=e;const{id:s,accessHash:a}=t,i=X(s,a);return sn(new g.Api.channels.ToggleSignatures({channel:i,enabled:n}),!0)}async function jn(e,t){let n,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"recent",a=arguments.length>3?arguments[3]:void 0;switch(s){case"kicked":n=new g.Api.ChannelParticipantsKicked({q:""});break;case"admin":n=new g.Api.ChannelParticipantsAdmins;break;default:n=new g.Api.ChannelParticipantsRecent}const i=await sn(new g.Api.channels.GetParticipants({channel:X(e,t),filter:n,offset:a,limit:200}));if(i&&!(i instanceof g.Api.channels.ChannelParticipantsNotModified))return ts(i),{members:Xe(i),users:i.users.map(it).filter(Boolean)}}async function $n(){const e=await sn(new g.Api.channels.GetGroupsForDiscussion);if(e)return ts(e),e.chats.map((e=>Ke(e)))}function Jn(e){let{channel:t,chat:n}=e;return sn(new g.Api.channels.SetDiscussionGroup({broadcast:J(t.id,t.accessHash),group:n?J(n.id,n.accessHash):new g.Api.InputChannelEmpty}),!0)}async function Qn(e){const t=await sn(new g.Api.messages.MigrateChat({chatId:X(e.id)}));if(t&&t instanceof g.Api.Updates)return ts(t),Ke(t.chats[1])}async function Xn(e){const t=await sn(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,megagroup:c}=t;n instanceof g.Api.Photo&&H(t.photo),gn({"@type":"showInvite",data:{title:a,about:r,hash:e,participantsCount:s,isChannel:i&&!c,isRequestNeeded:o,...n instanceof g.Api.Photo&&{photo:v(n)}}})}else n=Ke(t.chat),n&&gn({"@type":"updateChat",id:n.id,chat:n});return n?{chatId:n.id}:void 0}async function Zn(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];try{return"chatTypeChannel"===e.type||"chatTypeSuperGroup"===e.type?await sn(new g.Api.channels.InviteToChannel({channel:X(e.id,e.accessHash),users:t.map((e=>X(e.id,e.accessHash)))}),!0,n):await Promise.all(t.map((t=>sn(new g.Api.messages.AddChatUser({chatId:X(e.id),userId:X(t.id,t.accessHash)}),!0,n))))}catch(e){return}}function Yn(e,t){return"chatTypeChannel"===e.type||"chatTypeSuperGroup"===e.type?Hn({chat:e,user:t,bannedRights:{viewMessages:!0,sendMessages:!0,sendMedia:!0,sendStickers:!0,sendGifs:!0,sendGames:!0,sendInline:!0,embedLinks:!0,sendPolls:!0,changeInfo:!0,inviteUsers:!0,pinMessages:!0},untilDate:un}):sn(new g.Api.messages.DeleteChatUser({chatId:X(e.id),userId:X(t.id,t.accessHash)}),!0)}function es(e){const t={};return e.chats.forEach((e=>{t[`chat${e.id}`]=e})),e.users.forEach((e=>{t[`user${e.id}`]=e})),t}function ts(e){"users"in e&&K(e.users),"chats"in e&&K(e.chats),"messages"in e&&e.messages.forEach((e=>{e instanceof g.Api.Message&&ae(e)&&O(e)}))}async function ns(e){let{hash:t}=e;const n=await sn(new g.Api.messages.ImportChatInvite({hash:t}));if(n instanceof g.Api.Updates&&n.chats.length)return Ke(n.chats[0])}function ss(e){let{chat:t,enabledReactions:n}=e;return sn(new g.Api.messages.SetChatAvailableReactions({peer:J(t.id,t.accessHash),availableReactions:n}),!0)}function as(e){let{chat:t,isProtected:n}=e;const{id:s,accessHash:a}=t;return sn(new g.Api.messages.ToggleNoForwards({peer:J(s,a),enabled:n}),!0)}function is(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}),is(this,"name",void 0),Object.assign(this,s)}else super(e),is(this,"name",void 0);this.name=t}});var os=n(8764).Buffer;let rs;async function cs(e){let{chat:t,threadId:n,...s}=e;const a=-1===n?g.Api.messages.GetHistory:g.Api.messages.GetReplies;let i;try{i=await sn(new a({peer:J(t.id,t.accessHash),...-1!==n&&{msgId:n},...s}),void 0,!0)}catch(e){"CHANNEL_PRIVATE"===e.message&&rs({"@type":"updateChat",id:t.id,chat:{isRestricted:!0}})}if(!i||i instanceof g.Api.messages.MessagesNotModified||!i.messages)return;xs(i);const o=i.messages.map(_e).filter(Boolean),r=i.users.map(it).filter(Boolean),c=i.chats.map((e=>Ke(e))).filter(Boolean),l=o.map((e=>{let{threadInfo:t}=e;return t})).filter(Boolean);return{messages:o,users:r,chats:c,threadInfos:l}}async function ls(e){let{chat:t,messageId:n}=e;const s="channel"===j(t.id);let a;try{a=await sn(s?new g.Api.channels.GetMessages({channel:X(t.id,t.accessHash),id:[new g.Api.InputMessageID({id:n})]}):new g.Api.messages.GetMessages({id:[new g.Api.InputMessageID({id:n})]}),void 0,!0)}catch(e){const{message:t}=e;"CHANNEL_PRIVATE"!==t&&rs({"@type":"error",error:{message:t,isSlowMode:!1,hasErrorKey:!0}})}if(!a||a instanceof g.Api.messages.MessagesNotModified)return;const i=a.messages[0];if(!i)return;if(i instanceof g.Api.MessageEmpty)return"MESSAGE_DELETED";const o=i&&_e(i);return o?(i instanceof g.Api.Message&&O(i),{message:o,users:a.users.map(it).filter(Boolean)}):void 0}let ds=Promise.resolve();function us(e,t){let{chat:n,text:s,entities:a,replyingTo:i,attachment:o,sticker:r,gif:c,poll:l,contact:d,isSilent:u,scheduledAt:p,groupedId:f,noWebPage:h,sendAs:m,serverTimeOffset:_}=e;const y=function(e,t,n,s,a,i,o,r,c,l,d,u){let g=arguments.length>12&&void 0!==arguments[12]?arguments[12]:0;const p=he++,f=a&&Te(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&&xe(r,p),...c&&{contact:c}},date:d||Math.round(Date.now()/1e3)+g,isOutgoing:!h,senderId:(null==u?void 0:u.id)||fe,...s&&{replyToMessageId:s},...l&&{groupedId:l,...f&&(f.photo||f.video)&&{isInAlbum:!0}},...d&&{isScheduled:!0}}}(n,s,a,i,o,r,c,l,d,f,p,m,_);rs({"@type":y.isScheduled?"newScheduledMessage":"newMessage",id:y.id,chatId:n.id,message:y}),setTimeout((()=>{rs({"@type":y.isScheduled?"updateScheduledMessage":"updateMessage",id:y.id,chatId:n.id,message:{sendingState:"messageSendingStatePending"}})}),1e3);const b=te();if(C.localMessages[String(b)]=y,f)return function(e,t,n,s){let{chat:a,text:i,entities:o,replyingTo:r,attachment:c,groupedId:l,isSilent:d,scheduledAt:u,sendAs:p}=e,f=-1;gs[l]||(gs[l]={counter:0,singleMediaByIndex:{}}),f=gs[l].counter++;const h=ds;return ds=(async()=>{let e;try{e=await hs(n,c,s)}catch(e){return gs[l].counter--,void await h}const m=await async function(e,t){const n=await sn(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})})}}(J(a.id,a.accessHash),e);if(await h,!m)return void gs[l].counter--;if(gs[l].singleMediaByIndex[f]=new g.Api.InputSingleMedia({media:m,randomId:t,message:i||"",entities:o?o.map(se):void 0}),Object.keys(gs[l].singleMediaByIndex).length{let e;if(o)try{e=await hs(y,o,t)}catch(e){return void await w}else r?e=ee(r):c?e=ee(c):l?e=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((e=>{let{text:t,option:n}=e;return new g.Api.PollAnswer({text:t,option:W(n)})})),quiz:n.quiz,multipleChoice:n.multipleChoice});if(!s)return new g.Api.InputMediaPoll({poll:a});const i=s.correctAnswers.map(W),{solution:o}=s,r=s.solutionEntities?s.solutionEntities.map(se):[];return new g.Api.InputMediaPoll({poll:a,correctAnswers:i,...o&&{solution:o,solutionEntities:r}})}(l,b):d&&(e=new g.Api.InputMediaContact({phoneNumber:d.phoneNumber,firstName:d.firstName,lastName:d.lastName,vcard:""}));await w;const f=e?g.Api.messages.SendMedia:g.Api.messages.SendMessage;await sn(new f({clearDraft:!0,message:s||"",entities:a?a.map(se):void 0,peer:J(n.id,n.accessHash),randomId:b,...u&&{silent:u},...p&&{scheduleDate:p},...i&&{replyToMsgId:i},...e&&{media:e},...h&&{noWebpage:h},...m&&{sendAs:J(m.id,m.accessHash)}}),!0)})(),ds}const gs={};async function ps(e){let{chat:t,message:n,text:s,entities:a,noWebPage:i,serverTimeOffset:o}=e;const r=1e3*n.date>Date.now()+1e3*o,c={content:{...n.content,...s&&{text:{text:s,entities:a}}}};rs({"@type":r?"updateScheduledMessage":"updateMessage",id:n.id,chatId:t.id,message:c}),C.localMessages[n.id]={...n,...c};const l=a&&a.map(se);await sn(new g.Api.messages.EditMessage({message:s||"",entities:l,peer:J(t.id,t.accessHash),id:n.id,...r&&{scheduleDate:n.date},...i&&{noWebpage:i}}),!0)}async function fs(e){let{chat:t,message:n,scheduledAt:s}=e;await sn(new g.Api.messages.EditMessage({peer:J(t.id,t.accessHash),id:n.id,scheduleDate:s}),!0)}async function hs(e,t,n){const{filename:s,blobUrl:a,mimeType:i,quick:o,voice:l}=t,d=await async function(e,t){const n=await async function(e){return(await fetch(e)).blob()}(e);return function(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}(n,t)}(a,s),u=t=>{n.isCanceled?u.isCanceled=!0:n(t,e.id)},p=await rn(d,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(l){const{duration:e,waveform:t}=l,{data:n}=R(t,63);f.push(new g.Api.DocumentAttributeAudio({voice:!0,duration:e,waveform:os.from(n)}))}return new g.Api.InputMediaUploadedDocument({file:p,mimeType:i,attributes:f})}async function ms(e){let{chat:t,messageId:n,isUnpin:s,isOneSide:a,isSilent:i}=e;await sn(new g.Api.messages.UpdatePinnedMessage({peer:J(t.id,t.accessHash),id:n,...s&&{unpin:!0},...a&&{pmOneside:!0},...i&&{silent:!0}}),!0)}async function _s(e){let{chat:t}=e;await sn(new g.Api.messages.UnpinAllMessages({peer:J(t.id,t.accessHash)}),!0)}async function ys(e){let{chat:t,messageIds:n,shouldDeleteForAll:s}=e;const a="channel"===j(t.id);await sn(a?new g.Api.channels.DeleteMessages({channel:X(t.id,t.accessHash),id:n}):new g.Api.messages.DeleteMessages({id:n,...s&&{revoke:!0}}))&&rs({"@type":"deleteMessages",ids:n,...a&&{chatId:t.id}})}async function bs(e){let{chat:t,messageIds:n}=e;await sn(new g.Api.messages.DeleteScheduledMessages({peer:J(t.id,t.accessHash),id:n}))&&rs({"@type":"deleteScheduledMessages",ids:n,chatId:t.id})}async function ws(e){let{chat:t,shouldDeleteForAll:n,maxId:s}=e;const a="channel"===j(t.id);await sn(a?new g.Api.channels.DeleteHistory({channel:X(t.id,t.accessHash),maxId:s}):new g.Api.messages.DeleteHistory({peer:J(t.id,t.accessHash),...n&&{revoke:!0},...!n&&{just_clear:!0},maxId:s}))&&rs({"@type":"deleteHistory",chatId:t.id})}async function vs(e){let{peer:t,messageIds:n,reason:s,description:a}=e;return await sn(new g.Api.messages.Report({peer:J(t.id,t.accessHash),id:n,reason:de(s),message:a}))}async function Is(e){let{peer:t,threadId:n,action:s}=e;const a=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}}(s);if(a)return await sn(new g.Api.messages.SetTyping({peer:J(t.id,t.accessHash),topMsgId:n,action:a}))}async function Cs(e){let{chat:t,threadId:n,maxId:s,serverTimeOffset:a}=e;const i="channel"===j(t.id);i&&-1===n?await sn(new g.Api.channels.ReadHistory({channel:X(t.id,t.accessHash),maxId:s})):i?await sn(new g.Api.messages.ReadDiscussion({peer:J(t.id,t.accessHash),msgId:n,readMaxId:s})):await sn(new g.Api.messages.ReadHistory({peer:J(t.id,t.accessHash),maxId:s})),-1===n?yn({chat:t,serverTimeOffset:a,noLastMessage:!0}):Ss({chat:t,threadId:n})}async function As(e){let{chat:t,messageIds:n}=e;const s="channel"===j(t.id);await sn(s?new g.Api.channels.ReadMessageContents({channel:X(t.id,t.accessHash),id:n}):new g.Api.messages.ReadMessageContents({id:n})),rs({...s?{"@type":"updateChannelMessages",channelId:t.id}:{"@type":"updateCommonBoxMessages"},ids:n,messageUpdate:{hasUnreadMention:!1,isMediaUnread:!1}})}async function Ss(e){let{chat:t,threadId:n}=e;const[s,a]=await Promise.all([sn(new g.Api.messages.GetDiscussionMessage({peer:J(t.id,t.accessHash),msgId:n})),sn(new g.Api.messages.GetReplies({peer:J(t.id,t.accessHash),msgId:n,offsetId:1,addOffset:-1,limit:1}))]);if(!s||!s.messages.length)return;const i=q(s.messages[0]);return i?(rs({"@type":"updateThreadInfo",chatId:i,threadId:n,threadInfo:{threadId:n,topMessageId:s.messages[s.messages.length-1].id,lastReadInboxMessageId:s.readInboxMaxId,messagesCount:a instanceof g.Api.messages.ChannelMessages?a.count:void 0},firstMessageId:a&&"messages"in a&&a.messages.length?a.messages[0].id:void 0}),s.chats.map((e=>Ke(e))).filter(Boolean).forEach((e=>{rs({"@type":"updateChat",id:e.id,chat:e,noTopChatsRequest:!0})})),{discussionChatId:i}):void 0}async function Ps(e){let t,{chat:n,type:s,query:a,topMessageId:i,minDate:o,maxDate:r,...c}=e;switch(s){case"media":t=new g.Api.InputMessagesFilterPhotoVideo;break;case"documents":t=new g.Api.InputMessagesFilterDocument;break;case"links":t=new g.Api.InputMessagesFilterUrl;break;case"audio":t=new g.Api.InputMessagesFilterMusic;break;case"voice":t=new g.Api.InputMessagesFilterRoundVoice;break;case"profilePhoto":t=new g.Api.InputMessagesFilterChatPhotos;break;default:t=new g.Api.InputMessagesFilterEmpty}const l=await sn(new g.Api.messages.Search({peer:J(n.id,n.accessHash),filter:t,q:a||"",topMsgId:i,minDate:o,maxDate:r,...c}));if(!l||l instanceof g.Api.messages.MessagesNotModified||!l.messages)return;xs(l);const d=l.chats.map((e=>Ke(e))).filter(Boolean),u=l.users.map(it).filter(Boolean),p=l.messages.map(_e).filter(Boolean);let f,h=p.length;return(l instanceof g.Api.messages.MessagesSlice||l instanceof g.Api.messages.ChannelMessages)&&(h=l.count,p.length&&(f=p[p.length-1].id)),{chats:d,users:u,messages:p,totalCount:h,nextOffsetId:f}}async function Ms(e){let t,{query:n,offsetRate:s=0,limit:a,type:i="text",minDate:o,maxDate:r}=e;switch(i){case"media":t=new g.Api.InputMessagesFilterPhotoVideo;break;case"documents":t=new g.Api.InputMessagesFilterDocument;break;case"links":t=new g.Api.InputMessagesFilterUrl;break;case"audio":t=new g.Api.InputMessagesFilterMusic;break;case"voice":t=new g.Api.InputMessagesFilterRoundVoice;break;default:if(!(n||r&&o))return;t=new g.Api.InputMessagesFilterEmpty}const c=await sn(new g.Api.messages.SearchGlobal({q:n,offsetRate:s,offsetPeer:new g.Api.InputPeerEmpty,limit:a,filter:t,folderId:0,minDate:o,maxDate:r}));if(!c||c instanceof g.Api.messages.MessagesNotModified||!c.messages)return;xs({chats:c.chats,users:c.users,messages:c.messages});const l=c.chats.map((e=>Ke(e))).filter(Boolean),d=c.users.map(it).filter(Boolean),u=c.messages.map(_e).filter(Boolean);let p,f=u.length;return(c instanceof g.Api.messages.MessagesSlice||c instanceof g.Api.messages.ChannelMessages)&&(f=c.count,u.length&&(p=u[u.length-1].id)),{messages:u,users:d,chats:l,totalCount:f,nextRate:"nextRate"in c&&c.nextRate?c.nextRate:p}}async function ks(e){let{message:t}=e;const n=await sn(new g.Api.messages.GetWebPagePreview({message:t}));return n&&De(n)}async function Rs(e){let{chat:t,messageId:n,options:s}=e;const{id:a,accessHash:i}=t;await sn(new g.Api.messages.SendVote({peer:J(a,i),msgId:n,options:s.map(W)}),!0)}async function Us(e){let{chat:t,messageId:n,option:s,offset:a,limit:i,shouldResetVoters:o}=e;const{id:r,accessHash:c}=t,l=await sn(new g.Api.messages.GetPollVotes({peer:J(r,c),id:n,...s&&{option:W(s)},...a&&{offset:a},...i&&{limit:i}}));if(!l)return;xs({chats:[],users:l.users,messages:[]});const d=l.users.map(it).filter(Boolean),u=l.votes.map((e=>({userId:e.userId,date:e.date})));return{count:l.count,votes:u,users:d,nextOffset:l.nextOffset,shouldResetVoters:o}}async function Es(e){let{fromChat:t,toChat:n,messages:s,serverTimeOffset:a,isSilent:i,scheduledAt:o,sendAs:r}=e;const c=s.map((e=>{let{id:t}=e;return t})),l=s.map(te);s.forEach(((e,t)=>{const s=function(e,t,n,s){const a=he++,{content:i,chatId:o,id:r,senderId:c,groupedId:l,isInAlbum:d}=t,u=i.audio,g=e.id===fe&&(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:fe,sendingState:"messageSendingStatePending",groupedId:l,isInAlbum:d,...c!==fe&&!u&&{forwardInfo:{date:t.date,isChannelPost:!1,fromChatId:o,fromMessageId:r,senderUserId:c}},...s&&{isScheduled:!0}}}(n,e,a,o);C.localMessages[String(l[t])]=s,rs({"@type":s.isScheduled?"newScheduledMessage":"newMessage",id:s.id,chatId:n.id,message:s})})),await sn(new g.Api.messages.ForwardMessages({fromPeer:J(t.id,t.accessHash),toPeer:J(n.id,n.accessHash),randomId:l,id:c,...i&&{sil2ent:i},...o&&{scheduleDate:o},...r&&{sendAs:J(r.id,r.accessHash)}}),!0)}async function Ds(e){let{chat:t,timestamp:n}=e;const s=await sn(new g.Api.messages.GetHistory({peer:J(t.id,t.accessHash),offsetDate:n,addOffset:-1,limit:1}));if(s&&!(s instanceof g.Api.messages.MessagesNotModified)&&s.messages&&s.messages.length)return s.messages[0].id}async function Bs(e){let{chat:t}=e;const{id:n,accessHash:s}=t,a=await sn(new g.Api.messages.GetScheduledHistory({peer:J(n,s)}));if(a&&!(a instanceof g.Api.messages.MessagesNotModified)&&a.messages)return xs(a),{messages:a.messages.map(_e).filter(Boolean)}}async function Ts(e){let{chat:t,ids:n}=e;const{id:s,accessHash:a}=t;await sn(new g.Api.messages.SendScheduledMessages({peer:J(s,a),id:n}),!0)}function xs(e){K(e.users),K(e.chats),e.messages.forEach((e=>{(e instanceof g.Api.Message&&ae(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 Vs(e){let{chat:t}=e;const n=await sn(new g.Api.messages.Search({peer:J(t.id,t.accessHash),filter:new g.Api.InputMessagesFilterPinned,q:"",limit:50}));if(!n||n instanceof g.Api.messages.MessagesNotModified||!n.messages)return;xs(n);const s=n.chats.map((e=>Ke(e))).filter(Boolean),a=n.users.map(it).filter(Boolean);return{messages:n.messages.map(_e).filter(Boolean),users:a,chats:s}}async function Ns(e){let{chat:t,messageId:n}=e;const s=await sn(new g.Api.messages.GetMessageReadParticipants({peer:J(t.id,t.accessHash),msgId:n}));return s?s.map(String):void 0}async function Fs(e){let{chat:t}=e;const n=await sn(new g.Api.channels.GetSendAs({peer:J(t.id,t.accessHash)}));if(n)return K(n.users),K(n.chats),{users:n.users.map(it).filter(Boolean),chats:n.chats.map((e=>Ke(e))).filter(Boolean),ids:n.peers.map(F)}}function Ls(e){let{sendAs:t,chat:n}=e;return sn(new g.Api.messages.SaveDefaultSendAs({peer:J(n.id,n.accessHash),sendAs:J(t.id,t.accessHash)}))}async function qs(e){let{chat:t}=e;const n=await sn(new g.Api.channels.GetSponsoredMessages({channel:J(t.id,t.accessHash)}));if(n&&n.messages.length)return xs(n),{messages:n.messages.map(me).filter(Boolean),users:n.users.map(it).filter(Boolean),chats:n.chats.map((e=>Ke(e))).filter(Boolean)}}async function Os(e){let{chat:t,random:n}=e;await sn(new g.Api.channels.ViewSponsoredMessage({channel:J(t.id,t.accessHash),randomId:W(n)}))}let Hs,Gs,Ks,zs;async function Ws(e){let{id:t,accessHash:n}=e;const s=X(t,n);if(!(s instanceof g.Api.InputUser))return;const a=await sn(new g.Api.users.GetFullUser({id:s}));if(!a)return;const i=at(a);Hs({"@type":"updateUser",id:t,user:{fullInfo:i.fullInfo}})}async function js(e,t,n){const s=await sn(new g.Api.messages.GetCommonChats({userId:X(e,t),maxId:n?ue(n,j(n)):void 0,limit:100}));if(!s)return;sa(s);const a=[],i=[];return s.chats.forEach((e=>{const t=Ke(e);t&&(i.push(t),a.push(t.id))})),{chats:i,chatIds:a,isFullyLoaded:a.length<100}}async function $s(){const e=await sn(new g.Api.help.GetNearestDc);return null==e?void 0:e.country}async function Js(){const e=await sn(new g.Api.contacts.GetTopPeers({correspondents:!0}));if(!(e instanceof g.Api.contacts.TopPeers))return;const t=e.users.map(it).filter((e=>Boolean(e)&&!e.isSelf));return{ids:t.map((e=>{let{id:t}=e;return t})),users:t}}async function Qs(){const e=await sn(new g.Api.contacts.GetContacts({hash:E()("0")}));if(e&&!(e instanceof g.Api.contacts.ContactsNotModified))return e.users.forEach((e=>{e instanceof g.Api.User&&G(e,!0)})),{users:e.users.map(it).filter(Boolean),chats:e.users.map((e=>Ke(e))).filter(Boolean)}}async function Xs(e){let{users:t}=e;const n=await sn(new g.Api.users.GetUsers({id:t.map((e=>{let{id:t,accessHash:n}=e;return J(t,n)}))}));if(n&&n.length)return n.forEach((e=>{e instanceof g.Api.User&&G(e,!0)})),ct(n)}async function Zs(e){let{phone:t,firstName:n,lastName:s}=e;const a=await sn(new g.Api.contacts.ImportContacts({contacts:[ie({phone:t||"",firstName:n||"",lastName:s||""})]}));return a instanceof g.Api.contacts.ImportedContacts&&a.users.length&&G(a.users[0]),null!=a&&a.imported.length?N(a.imported[0].userId,"user"):void 0}function Ys(e){let{id:t,accessHash:n,phoneNumber:s="",firstName:a="",lastName:i="",shouldSharePhoneNumber:o=!1}=e;return sn(new g.Api.contacts.AddContact({id:X(t,n),firstName:a,lastName:i,phone:s,...o&&{addPhonePrivacyException:o}}),!0)}async function ea(e){let{id:t,accessHash:n}=e;const s=X(t,n);s instanceof g.Api.InputUser&&await sn(new g.Api.contacts.DeleteContacts({id:[s]}))&&Hs({"@type":"deleteContact",id:t})}async function ta(e,t){if(e){const{id:t,accessHash:n}=e,s=await sn(new g.Api.photos.GetUserPhotos({userId:X(t,n),limit:40,offset:0,maxId:E()("0")}));if(!s)return;return sa(s),{photos:s.photos.filter((e=>e instanceof g.Api.Photo)).map(v)}}const n=await Ps({chat: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 na(e){const{id:t,accessHash:n}=e;return sn(new g.Api.messages.ReportSpam({peer:J(t,n)}),!0)}function sa(e){"chats"in e&&K(e.chats),"photos"in e&&e.photos.forEach(H)}async function aa(e){let{hash:t="0"}=e;const n=await sn(new g.Api.messages.GetAllStickers({hash:E()(t)}));if(n&&!(n instanceof g.Api.messages.AllStickersNotModified))return n.sets.forEach((e=>{var t;null!==(t=e.thumbs)&&void 0!==t&&t.length&&(C.stickerSets[String(e.id)]=e)})),{hash:String(n.hash),sets:n.sets.map(M)}}async function ia(e){let{hash:t="0"}=e;const n=await sn(new g.Api.messages.GetRecentStickers({hash:E()(t)}));if(n&&!(n instanceof g.Api.messages.RecentStickersNotModified))return{hash:String(n.hash),stickers:wa(n.stickers.slice(0,20))}}async function oa(e){let{hash:t="0"}=e;const n=await sn(new g.Api.messages.GetFavedStickers({hash:E()(t)}));if(n&&!(n instanceof g.Api.messages.FavedStickersNotModified))return{hash:String(n.hash),stickers:wa(n.stickers)}}async function ra(e){let{hash:t="0"}=e;const n=await sn(new g.Api.messages.GetFeaturedStickers({hash:E()(t)}));if(n&&!(n instanceof g.Api.messages.FeaturedStickersNotModified))return{hash:String(n.hash),sets:n.sets.map(k)}}async function ca(e){let{sticker:t,unfave:n}=e;const s=new g.Api.messages.FaveSticker({id:Y(t),unfave:n});await sn(s)&&Gs({"@type":"updateFavoriteStickers"})}async function la(e){let{stickerSetShortName:t,stickerSetId:n,accessHash:s}=e;const a=await sn(new g.Api.messages.GetStickerSet({stickerset:n?Z(n,s):(i=t,new g.Api.InputStickerSetShortName({shortName:i}))}));var i,o;if(a instanceof g.Api.messages.StickerSet)return{set:M(a.set),stickers:wa(a.documents),packs:(o=a.packs,o.reduce(((e,t)=>{let{emoticon:n,documents:s}=t;return e[n]=s.map((e=>P(C.documents[String(e)]))).filter(Boolean),e}),{}))}}async function da(){const e=await sn(new g.Api.messages.GetStickerSet({stickerset:new g.Api.InputStickerSetAnimatedEmoji}));if(e instanceof g.Api.messages.StickerSet)return{set:M(e.set),stickers:wa(e.documents)}}async function ua(){const e=await sn(new g.Api.messages.GetStickerSet({stickerset:new g.Api.InputStickerSetAnimatedEmojiAnimations}));if(e instanceof g.Api.messages.StickerSet)return{set:M(e.set),stickers:wa(e.documents)}}async function ga(e){let{query:t,hash:n="0"}=e;const s=await sn(new g.Api.messages.SearchStickerSets({q:t,hash:E()(n)}));if(s&&!(s instanceof g.Api.messages.FoundStickerSetsNotModified))return{hash:String(s.hash),sets:s.sets.map(k)}}async function pa(e){let{hash:t="0"}=e;const n=await sn(new g.Api.messages.GetSavedGifs({hash:E()(t)}));if(n&&!(n instanceof g.Api.messages.SavedGifsNotModified))return{hash:String(n.hash),gifs:va(n.gifs)}}function fa(e){let{gif:t,shouldUnsave:n}=e;return sn(new g.Api.messages.SaveGif({id:Y(t),unsave:n}),!0)}async function ha(e){let{stickerSetId:t,accessHash:n}=e;await sn(new g.Api.messages.InstallStickerSet({stickerset:Z(t,n)}))&&Gs({"@type":"updateStickerSet",id:t,stickerSet:{installedDate:Date.now()}})}async function ma(e){let{stickerSetId:t,accessHash:n}=e;await sn(new g.Api.messages.UninstallStickerSet({stickerset:Z(t,n)}))&&Gs({"@type":"updateStickerSet",id:t,stickerSet:{installedDate:void 0}})}async function _a(e){let{query:t,offset:n=""}=e;if(!Ks){const e=await sn(new g.Api.help.GetConfig);if(!e)return;const t=await sn(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 s=await sn(new g.Api.messages.GetInlineBotResults({bot:Ks,peer:new g.Api.InputPeerEmpty,query:t,offset:n}));if(!s)return;const a=s.results.map((e=>{if(e instanceof g.Api.BotInlineMediaResult)return e.document})).filter(Boolean);return{nextOffset:s.nextOffset,gifs:va(a)}}async function ya(e){let{emoji:t,hash:n="0"}=e;const s=await sn(new g.Api.messages.GetStickers({emoticon:t,hash:E()(n)}));if(s&&!(s instanceof g.Api.messages.StickersNotModified))return{stickers:wa(s.stickers),hash:String(s.hash)}}async function ba(e){let{language:t,fromVersion:n}=e;const s=await sn(new g.Api.messages.GetEmojiKeywordsDifference({langCode:t,fromVersion:n}));if(s)return{language:s.langCode,version:s.version,keywords:s.keywords.reduce(((e,t)=>(e[t.keyword]=t.emoticons,e)),{})}}function wa(e){return e.map((e=>{if(e instanceof g.Api.Document){const t=P(e);if(t)return C.documents[String(e.id)]=e,t}})).filter(Boolean)}function va(e){return e.map((e=>{if(e instanceof g.Api.Document){const t=Me(e);if(t)return C.documents[String(e.id)]=e,t}})).filter(Boolean)}function Ia(e){let{username:t}=e;return sn(new g.Api.channels.CheckUsername({channel:new g.Api.InputChannelEmpty,username:t}))}async function Ca(e){let{chat:t,username:n}=e;await sn(new g.Api.channels.UpdateUsername({channel:X(t.id,t.accessHash),username:n}))&&zs({"@type":"updateChat",id:t.id,chat:{username:n}})}async function Aa(e){let{chat:t,usageLimit:n,expireDate:s}=e;const a=await sn(new g.Api.messages.ExportChatInvite({peer:J(t.id,t.accessHash),usageLimit:n,expireDate:s}));if(a)return zs({"@type":"updateChatFullInfo",id:t.id,fullInfo:{inviteLink:a.link}}),a.link}async function Sa(e){let{peer:t,admin:n,limit:s=0,isRevoked:a}=e;const i=await sn(new g.Api.messages.GetExportedChatInvites({peer:J(t.id,t.accessHash),adminId:X(n.id,n.accessHash),limit:s,revoked:a||void 0}));if(i)return K(i.users),i.invites.map(nt)}async function Pa(e){let{peer:t,isRevoked:n,link:s,expireDate:a,usageLimit:i,isRequestNeeded:o,title:r}=e;const c=await sn(new g.Api.messages.EditExportedChatInvite({link:s,peer:J(t.id,t.accessHash),expireDate:a,usageLimit:o?void 0:i,requestNeeded:o,title:r,revoked:n||void 0}));if(c){if(K(c.users),c instanceof g.Api.messages.ExportedChatInvite){const e=nt(c.invite);return{oldInvite:e,newInvite:e}}if(c instanceof g.Api.messages.ExportedChatInviteReplaced)return{oldInvite:nt(c.invite),newInvite:nt(c.newInvite)}}}async function Ma(e){let{peer:t,expireDate:n,usageLimit:s,isRequestNeeded:a,title:i}=e;const o=await sn(new g.Api.messages.ExportChatInvite({peer:J(t.id,t.accessHash),expireDate:n,usageLimit:a?void 0:s,requestNeeded:a||void 0,title:i}));if(o)return nt(o)}async function ka(e){let{peer:t,link:n}=e;return await sn(new g.Api.messages.DeleteExportedChatInvite({peer:J(t.id,t.accessHash),link:n}))}async function Ra(e){let{peer:t,admin:n}=e;return await sn(new g.Api.messages.DeleteRevokedExportedChatInvites({peer:J(t.id,t.accessHash),adminId:X(n.id,n.accessHash)}))}async function Ua(e){let{peer:t,link:n,offsetDate:s=0,offsetUser:a,limit:i=0,isRequested:o}=e;const r=await sn(new g.Api.messages.GetChatInviteImporters({peer:J(t.id,t.accessHash),link:n,offsetDate:s,offsetUser:a?X(a.id,a.accessHash):new g.Api.InputUserEmpty,limit:i,requested:o||void 0}));if(r)return K(r.users),r.importers.map((e=>function(e){const{userId:t,date:n,about:s,requested:a}=e;return{userId:N(t,"user"),date:n,about:s,isRequested:a}}(e)))}function Ea(e){let{peer:t,user:n,isApproved:s}=e;return sn(new g.Api.messages.HideChatJoinRequest({peer:J(t.id,t.accessHash),userId:X(n.id,n.accessHash),approved:s||void 0}),!0)}function Da(e){let{peer:t,isApproved:n,link:s}=e;return sn(new g.Api.messages.HideAllChatJoinRequests({peer:J(t.id,t.accessHash),approved:n||void 0,link:s}),!0)}function Ba(e){const{id:t,accessHash:n}=e;return sn(new g.Api.messages.HidePeerSettingsBar({peer:J(t,n)}))}const Ta={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"},xa={};let Va,Na,Fa;async function La(){const e=await sn(new g.Api.account.GetPassword);if(!e)return;const{hint:t,hasPassword:n}=e;return{hint:t,hasPassword:n}}function qa(e){return Va({"@type":"updateTwoFaStateWaitCode",length:e}),new Promise(((e,t)=>{xa.resolve=e,xa.reject=t}))}async function Oa(e){try{return await cn({isCheckPassword:!0,currentPassword:e}),!0}catch(e){return Wa(e),!1}}async function Ha(e){try{return await cn({currentPassword:e}),!0}catch(e){return Wa(e),!1}}async function Ga(e,t,n,s){try{return await cn({currentPassword:e,newPassword:t,hint:n,email:s,emailCodeCallback:qa,onEmailCodeError:Wa}),!0}catch(e){return Wa(e),!1}}async function Ka(e,t){try{return await cn({currentPassword:e,newPassword:e,email:t,emailCodeCallback:qa,onEmailCodeError:Wa}),!0}catch(e){return Wa(e),!1}}function za(e){xa.resolve(e)}function Wa(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=Ta[e.message];t||(t="Unexpected Error"),Va({"@type":"updateTwoFaError",message:t})}async function ja(e){let{call:t}=e;const n=await sn(new g.Api.phone.GetGroupCall({call:ge(t)}));if(!n)return;K(n.users),K(n.chats);const s=n.users.map(it).filter(Boolean),a=n.chats.map((e=>Ke(e))).filter(Boolean);return{groupCall:yt(n.call),users:s,chats:a}}function $a(e){let{call:t}=e;return sn(new g.Api.phone.DiscardGroupCall({call:ge(t)}),!0)}function Ja(e){let{call:t,participant:n,muted:s,presentationPaused:a,videoStopped:i,videoPaused:o,volume:r,raiseHand:c}=e;return sn(new g.Api.phone.EditGroupCallParticipant({call:ge(t),participant:J(n.id,n.accessHash),...void 0!==i&&{videoStopped:i},...void 0!==o&&{videoPaused:o},...void 0!==s&&{muted:s},...void 0!==a&&{presentationPaused:a},...void 0!==c&&{raiseHand:c},...void 0!==r&&{volume:r}}),!0)}function Qa(e){let{groupCall:t,title:n}=e;return sn(new g.Api.phone.EditGroupCallTitle({title:n,call:ge(t)}),!0)}async function Xa(e){let{call:t,canSelfUnmute:n}=e;const s=await sn(new g.Api.phone.ExportGroupCallInvite({canSelfUnmute:n||void 0,call:ge(t)}));if(s)return s.link}async function Za(e){let{call:t,offset:n}=e;const s=await sn(new g.Api.phone.GetGroupParticipants({call:ge(t),ids:[],sources:[],offset:n||"",limit:100}));if(!s)return;K(s.users),K(s.chats);const a=s.users.map(it).filter(Boolean),i=s.chats.map((e=>Ke(e))).filter(Boolean);return Na({"@type":"updateGroupCallParticipants",groupCallId:t.id,participants:s.participants.map(ht),nextOffset:s.nextOffset}),{users:a,chats:i}}function Ya(e){let{call:t}=e;return sn(new g.Api.phone.LeaveGroupCall({call:ge(t)}),!0)}async function ei(e){let{call:t,inviteHash:n,params:s}=e;const a=await sn(new g.Api.phone.JoinGroupCall({call:ge(t),joinAs:new g.Api.InputPeerSelf,muted:!0,videoStopped:!0,params:new g.Api.DataJSON({data:JSON.stringify(s)}),inviteHash:n}));if(a&&a instanceof g.Api.Updates){const e=a.updates.find((e=>e instanceof g.Api.UpdateGroupCall));if(!(e instanceof g.Api.UpdateGroupCall))return;return yt(e.call)}}async function ti(e){let{peer:t}=e;const n=(0,D.readBigIntFromBuffer)((0,D.generateRandomBytes)(4),!0,!0).toJSNumber(),s=await sn(new g.Api.phone.CreateGroupCall({peer:J(t.id,t.accessHash),randomId:n}));if(s&&s instanceof g.Api.Updates){const e=s.updates[0];if(e instanceof g.Api.UpdateGroupCall)return yt(e.call)}}function ni(e){let{call:t,params:n}=e;return sn(new g.Api.phone.JoinGroupCallPresentation({call:ge(t),params:new g.Api.DataJSON({data:JSON.stringify(n)})}),!0)}function si(e){let{call:t,subscribed:n}=e;return sn(new g.Api.phone.ToggleGroupCallStartSubscription({call:ge(t),subscribed:n}),!0)}function ai(e){let{call:t}=e;return sn(new g.Api.phone.LeaveGroupCallPresentation({call:ge(t)}),!0)}function ii(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((e=>{let{label:t,amount:n}=e;return{label:t,amount:Number(n.value)}}))})))}async function oi(e){let{chat:t,messageId:n,requestInfo:s,shouldSave:a}=e;const i=await sn(new g.Api.payments.ValidateRequestedInfo({peer:J(t.id,t.accessHash),msgId:n,save:a||void 0,info:ce(s)}));if(!i)return;const{id:o,shippingOptions:r}=i;return o?{id:o,shippingOptions:ii(r)}:void 0}async function ri(e){let{chat:t,messageId:n,formId:s,requestedInfoId:a,shippingOptionId:i,credentials:o}=e;const r=await sn(new g.Api.payments.SendPaymentForm({formId:E()(s),peer:J(t.id,t.accessHash),msgId:n,requestedInfoId:a,shippingOptionId:i,credentials:new g.Api.InputPaymentCredentials({save:o.save,data:new g.Api.DataJSON({data:JSON.stringify(o.data)})})}));if(!(r instanceof g.Api.payments.PaymentVerificationNeeded))return Boolean(r);Fa({"@type":"updatePaymentVerificationNeeded",url:r.url})}async function ci(e){let{chat:t,messageId:n}=e;const s=await sn(new g.Api.payments.GetPaymentForm({peer:J(t.id,t.accessHash),msgId:n}));if(s)return function(e){const{formId:t,canSaveCredentials:n,passwordMissing:s,providerId:a,nativeProvider:i,nativeParams:o,savedInfo:r,invoice:c}=e,{test:l,nameRequested:d,phoneRequested:u,emailRequested:g,shippingAddressRequested:p,flexible:f,phoneToProvider:h,emailToProvider:m,currency:_,prices:y}=c,b=y.map((e=>{let{label:t,amount:n}=e;return{label:t,amount:Number(n.value)}})),w=o?JSON.parse(o.data):{};return{canSaveCredentials:n,passwordMissing:s,formId:String(t),providerId:String(a),nativeProvider:i,savedInfo:r,invoice:{test:l,nameRequested:d,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,publicToken:null==w?void 0:w.public_token}}}(s)}async function li(e,t){const n=await sn(new g.Api.payments.GetPaymentReceipt({peer:J(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:l}=n||{},{prices:d}=t,u=d.map((e=>{let{label:t,amount:n}=e;return{label:t,amount:Number(n.value)}}));let g,p;return s&&(g=s.prices.map((e=>{let{label:t,amount:n}=e;return{label:t,amount:Number(n.value)}})),p=s.title),{currency:a,prices:u,info:{shippingAddress:r,phone:c,name:l},totalAmount:Number(i.value),credentialsTitle:o,shippingPrices:g,shippingMethod:p}}(n)}var di=n(8764).Buffer;function ui(e){const{emojies_sounds:t}=e;return Object.keys(t).reduce(((e,n)=>{const s=t[n];return C.documents[s.id]=new g.Api.Document({id:E()(s.id),accessHash:E()(s.access_hash),dcId:1,mimeType:"audio/ogg",fileReference:di.from(atob(s.file_reference_base64.replace(/-/g,"+").replace(/_/g,"/")))}),e[n]=s.id,e}),{})}const gi=["ar","fa","id","ko","uz"];function pi(e){let{firstName:t,lastName:n,about:s}=e;return sn(new g.Api.account.UpdateProfile({firstName:t||"",lastName:n||"",about:s||""}),!0)}function fi(e){return sn(new g.Api.account.CheckUsername({username:e}))}function hi(e){return sn(new g.Api.account.UpdateUsername({username:e}),!0)}async function mi(e){const t=await rn(e);return sn(new g.Api.photos.UploadProfilePhoto({file:t}),!0)}async function _i(e){const t=await rn(e);await sn(new g.Api.photos.UploadProfilePhoto({file:t}))}async function yi(){const e=await sn(new g.Api.account.GetWallPapers({hash:E()("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=>{C.documents[String(e.document.id)]=e.document})),{wallpapers:t.map(lt).filter(Boolean)}}async function bi(e){const t=await rn(e),n=await sn(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=lt(n);return s?(C.documents[String(n.document.id)]=n.document,{wallpaper:s}):void 0}async function wi(){const e=await sn(new g.Api.contacts.GetBlocked({limit:100}));if(e)return Oi(e),{users:e.users.map(it).filter(Boolean),chats:e.chats.map((e=>Ke(e,void 0,!0))).filter(Boolean),blockedIds:e.blocked.map((e=>F(e.peerId))),totalCount:e instanceof g.Api.contacts.BlockedSlice?e.count:e.blocked.length}}function vi(e,t){return sn(new g.Api.contacts.Block({id:J(e,t)}))}function Ii(e,t){return sn(new g.Api.contacts.Unblock({id:J(e,t)}))}async function Ci(){const e=await sn(new g.Api.account.GetAuthorizations);if(e)return e.authorizations.map(dt)}function Ai(e){return sn(new g.Api.account.ResetAuthorization({hash:E()(e)}))}function Si(){return sn(new g.Api.auth.ResetAuthorizations)}async function Pi(e){let{serverTimeOffset:t}=e;const n=await sn(new g.Api.account.GetNotifyExceptions({compareSound:!0}),void 0,void 0,!0);if(n instanceof g.Api.Updates||n instanceof g.Api.UpdatesCombined)return Oi(n),n.updates.reduce(((e,n)=>n instanceof g.Api.UpdateNotifySettings&&n.peer instanceof g.Api.NotifyPeer?(e.push(gt(n.notifySettings,n.peer.peer,t)),e):e),[])}async function Mi(e){let{serverTimeOffset:t}=e;const[n,s,a,i]=await Promise.all([sn(new g.Api.account.GetContactSignUpNotification),sn(new g.Api.account.GetNotifySettings({peer:new g.Api.InputNotifyUsers})),sn(new g.Api.account.GetNotifySettings({peer:new g.Api.InputNotifyChats})),sn(new g.Api.account.GetNotifySettings({peer:new g.Api.InputNotifyBroadcasts}))]);if(!s||!a||!i)return!1;const{silent:o,muteUntil:r,showPreviews:c}=s,{silent:l,muteUntil:d,showPreviews:u}=a,{silent:p,muteUntil:f,showPreviews:h}=i;return{hasContactJoinedNotifications:!n,hasPrivateChatsNotifications:!(o||"number"==typeof r&&Fe(t)sn(new g.Api.langpack.GetLangPack({langPack:e,langCode:gi.includes(n)?`${n}-raw`:n})))))).filter(Boolean).map((e=>p(e.strings.map(_),"key")));if(s.length)return{langPack:Object.assign({},...s.reverse())}}async function Di(e){let{langPack:t,langCode:n,keys:s}=e;const a=await sn(new g.Api.langpack.GetStrings({langPack:t,langCode:gi.includes(n)?`${n}-raw`:n,keys:s}));if(a)return a.map(_)}async function Bi(e){const t=le(e),n=await sn(new g.Api.account.GetPrivacy({key:t}));if(n)return Oi(n),ut(n.rules)}function Ti(e){const t=Xt.session.getAuthKey().getKey();return sn(new g.Api.account.RegisterDevice({tokenType:10,secret:t,appSandbox:!1,otherUids:[],token:e}))}function xi(e){return sn(new g.Api.account.UnregisterDevice({tokenType:10,otherUids:[],token:e}))}async function Vi(e,t){const n=le(e),s=[];switch(t.allowedUsers&&s.push(new g.Api.InputPrivacyValueAllowUsers({users:t.allowedUsers.map((e=>{let{id:t,accessHash:n}=e;return X(t,n)}))})),t.allowedChats&&s.push(new g.Api.InputPrivacyValueAllowChatParticipants({chats:t.allowedChats.map((e=>{let{id:t}=e;return X(t)}))})),t.blockedUsers&&s.push(new g.Api.InputPrivacyValueDisallowUsers({users:t.blockedUsers.map((e=>{let{id:t,accessHash:n}=e;return X(t,n)}))})),t.blockedChats&&s.push(new g.Api.InputPrivacyValueDisallowChatParticipants({chats:t.blockedChats.map((e=>{let{id:t}=e;return X(t)}))})),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 sn(new g.Api.account.SetPrivacy({key:n,rules:s}));if(a)return Oi(a),ut(a.rules)}async function Ni(e){await sn(new g.Api.account.UpdateStatus({offline:!e}))}async function Fi(){const e=await sn(new g.Api.account.GetContentSettings);if(e)return{isSensitiveEnabled:Boolean(e.sensitiveEnabled),canChangeSensitive:Boolean(e.sensitiveCanChange)}}function Li(e){return sn(new g.Api.account.SetContentSettings({sensitiveEnabled:e||void 0}))}async function qi(){const e=await sn(new g.Api.help.GetAppConfig);if(e)return function(e){const t=ft(e);return{emojiSounds:ui(t),defaultReaction:t.reactions_default,seenByMaxChatMembers:t.chat_read_mark_size_threshold,seenByExpiresAt:t.chat_read_mark_expire_period}}(e)}function Oi(e){K(e.users),K(e.chats)}async function Hi(e){let{langCode:t="en"}=e;const n=await sn(new g.Api.help.GetCountriesList({langCode:t}));if(n instanceof g.Api.help.CountriesList)return s=n.countries,{phoneCodes:(a=s.filter((e=>!e.hidden)).map((e=>e.countryCodes.map((t=>pt(e,t))))),a.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:s.filter((e=>!e.hidden)).map((e=>pt(e))).sort(((e,t)=>e.name?e.name.localeCompare(t.name):e.defaultName.localeCompare(t.defaultName)))};var s,a}function Gi(e){return e?f(e,["url","mimeType"]):void 0}async function Ki(e){let{chatId:t,accessHash:n,messageId:s,data:a}=e;const i=await sn(new g.Api.messages.GetBotCallbackAnswer({peer:J(t,n),msgId:s,data:W(a)}));return i?_(i):void 0}async function zi(){const e=await sn(new g.Api.contacts.GetTopPeers({botsInline:!0}));if(!(e instanceof g.Api.contacts.TopPeers))return;const t=e.users.map(it).filter(Boolean);return{ids:t.map((e=>{let{id:t}=e;return t})),users:t}}async function Wi(e){let{username:t}=e;const n=await sn(new g.Api.contacts.ResolveUsername({username:t}));if(n&&n.users[0]instanceof g.Api.User&&n.users[0].bot&&n.users[0].botInlinePlaceholder)return G(n.users[0]),{user:it(n.users[0]),chat:Ke(n.users[0])}}async function ji(e){let{bot:t,chat:n,query:s,offset:a=""}=e;const i=await sn(new g.Api.messages.GetInlineBotResults({bot:J(t.id,t.accessHash),peer:J(n.id,n.accessHash),query:s,offset:a}));var o,r,c,l,d;if(i)return K(i.users),{isGallery:Boolean(i.gallery),help:t.botPlaceholder,nextOffset:(l=t.username,d=i.nextOffset,"gif"===l&&"0"===d?"":d),switchPm:(c=i.switchPm,c?f(c,["text","startParam"]):void 0),users:i.users.map(it).filter(Boolean),results:(o=String(i.queryId),r=i.results,r.map((e=>{return e instanceof g.Api.BotInlineMediaResult?(e.document instanceof g.Api.Document&&(t=e.document,C.documents[String(t.id)]=t),e.photo instanceof g.Api.Photo&&(n=e.photo,C.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:P(r)},...o instanceof g.Api.Photo&&{photo:v(o)},..."gif"===s&&r instanceof g.Api.Document&&{gif:Me(r)},..."video"===s&&r instanceof g.Api.Document&&{thumbnail:w(r.thumbs)}}}(e,o)):(e.thumb&&(s=e.thumb,C.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:Gi(r)}}(e,o));var t,n,s})))}}async function $i(e){let{chat:t,resultId:n,queryId:s,replyingTo:a,sendAs:i,isSilent:o,scheduleDate:r}=e;const c=te();await sn(new g.Api.messages.SendInlineBotResult({clearDraft:!0,randomId:c,queryId:E()(s),peer:J(t.id,t.accessHash),id:n,scheduleDate:r,...o&&{silent:!0},...a&&{replyToMsgId:a},...i&&{sendAs:J(i.id,i.accessHash)}}),!0)}async function Ji(e){let{bot:t,startParam:n}=e;const s=te();await sn(new g.Api.messages.StartBot({bot:J(t.id,t.accessHash),peer:J(t.id,t.accessHash),randomId:s,startParam:n}),!0)}function Qi(e){let{chat:t,emoticon:n}=e;return sn(new g.Api.messages.SetTyping({peer:J(t.id,t.accessHash),action:new g.Api.SendMessageEmojiInteractionSeen({emoticon:n})}))}function Xi(e){let{chat:t,emoticon:n,messageId:s,timestamps:a}=e;return sn(new g.Api.messages.SetTyping({peer:J(t.id,t.accessHash),action:new g.Api.SendMessageEmojiInteraction({emoticon:n,msgId:s,interaction:new g.Api.DataJSON({data:JSON.stringify({v:1,a:a.map((e=>({t:e,i:1})))})})})}))}async function Zi(){const e=await sn(new g.Api.messages.GetAvailableReactions({}));if(e&&!(e instanceof g.Api.messages.AvailableReactionsNotModified))return e.reactions.forEach((e=>{e.staticIcon instanceof g.Api.Document&&(C.documents[String(e.staticIcon.id)]=e.staticIcon),e.selectAnimation instanceof g.Api.Document&&(C.documents[String(e.selectAnimation.id)]=e.selectAnimation),e.aroundAnimation instanceof g.Api.Document&&(C.documents[String(e.aroundAnimation.id)]=e.aroundAnimation),e.centerIcon instanceof g.Api.Document&&(C.documents[String(e.centerIcon.id)]=e.centerIcon)})),e.reactions.map(Ie)}function Yi(e){let{chat:t,messageId:n,reaction:s}=e;return sn(new g.Api.messages.SendReaction({...s&&{reaction:s},peer:J(t.id,t.accessHash),msgId:n}),!0)}function eo(e){let{ids:t,chat:n}=e;return sn(new g.Api.messages.GetMessagesReactions({id:t,peer:J(n.id,n.accessHash)}),!0)}async function to(e){let{chat:t,messageId:n,reaction:s,offset:a}=e;const i=await sn(new g.Api.messages.GetMessageReactionsList({peer:J(t.id,t.accessHash),id:n,...s&&{reaction:s},limit:100,...a&&{offset:a}}));if(!i)return;K(i.users);const{nextOffset:o,reactions:r,count:c}=i;return{users:i.users.map(it).filter(Boolean),nextOffset:o,reactions:r.map(ve),count:c}}function no(e){let{reaction:t}=e;return sn(new g.Api.messages.SetDefaultReaction({reaction:t}))}function so(e,t){if(e.error)throw new Error(e.error);const n=JSON.parse(e.json.data),[s,...a]=n.columns,i=n.y_scaled;return{type:t?"area":n.types.y0,zoomToken:e.zoomToken,labelFormatter:n.xTickFormatter,tooltipFormatter:n.xTooltipFormatter,labels:s.slice(1),hideCaption:!n.subchart.show,hasSecondYAxis:i,isStacked:n.stacked&&!i,isPercentage:t,datasets:a.map((e=>{const t=e[0];return{name:n.names[t],color:(s=n.colors[t],s.substring(s.indexOf("#"))),values:e.slice(1)};var s})),...ao(n.subchart.defaultZoom,s.slice(1))}}function ao(e,t){const[n,s]=e;let a=0,i=t.length-1;return t.forEach(((e,t)=>{!a&&e>=n&&(a=t),!i&&e>=s&&(i=t)})),{minimapRange:{begin:Math.max(0,a/(t.length-1)),end:Math.min(1,i/(t.length-1))},labelFromIndex:a,labelToIndex:i}}function io(e){let{current:t,previous:n}=e;const s=t-n;return{current:t,change:s,...n&&{percentage:(s?Math.abs(s)/n*100:0).toFixed(2)}}}async function oo(e){let{chat:t}=e;const n=await sn(new g.Api.stats.GetBroadcastStats({channel:X(t.id,t.accessHash)}),void 0,void 0,void 0,t.fullInfo.statisticsDcId);var s,a;if(n)return{growthGraph:so((s=n).growthGraph),followersGraph:so(s.followersGraph),muteGraph:so(s.muteGraph),topHoursGraph:so(s.topHoursGraph),languagesGraph:s.languagesGraph.token,viewsBySourceGraph:s.viewsBySourceGraph.token,newFollowersBySourceGraph:s.newFollowersBySourceGraph.token,interactionsGraph:s.interactionsGraph.token,followers:io(s.followers),viewsPerPost:io(s.viewsPerPost),sharesPerPost:io(s.sharesPerPost),enabledNotifications:(a=s.enabledNotifications,{percentage:(a.part/a.total*100).toFixed(2)}),recentTopMessages:s.recentMessageInteractions}}async function ro(e){let{chat:t}=e;const n=await sn(new g.Api.stats.GetMegagroupStats({channel:X(t.id,t.accessHash)}),void 0,void 0,void 0,t.fullInfo.statisticsDcId);var s,a;if(n)return{growthGraph:so((s=n).growthGraph),membersGraph:so(s.membersGraph),topHoursGraph:so(s.topHoursGraph),languagesGraph:s.languagesGraph.token,messagesGraph:s.messagesGraph.token,actionsGraph:s.actionsGraph.token,period:(a=s.period,{maxDate:a.maxDate,minDate:a.minDate}),members:io(s.members),viewers:io(s.viewers),messages:io(s.messages),posters:io(s.posters)}}async function co(e){let{token:t,x:n,isPercentage:s,dcId:a}=e;const i=await sn(new g.Api.stats.LoadAsyncGraph({token:t,...n&&{x:E()(n)}}),void 0,void 0,void 0,a);if(i)return so(i,s)}let lo;async function uo(e,t){lo=e,function(e){bt=e}(mo),function(e){Mt=e}(mo),function(e){gn=e}(mo),function(e){rs=e}(mo),function(e){Hs=e}(mo),function(e){Gs=e}(mo),function(e){zs=e}(mo),function(e){Va=e}(mo),function(e){Na=e}(mo),function(e){Fa=e}(mo),await async function(e,t){Qt=e;const{userAgent:n,platform:s,sessionData:a,isTest:i,isMovSupported:o,isWebmSupported:r}=t,c=new g.sessions.CallbackSession(a,tn);self.isMovSupported=o,self.isWebmSupported=r,Xt=new g.TelegramClient(c,"2496","8da85b0d5bfe62527e5b244c209159c3",{deviceModel:navigator.userAgent||n||"Unknown UserAgent",systemVersion:s||"Unknown platform",appVersion:"1.38.1 Z",useWSS:!0,additionalDcsDisabled:!1,testServers:i}),Xt.addEventHandler(nn,Jt),Xt.addEventHandler(At,Jt);try{try{await Xt.start({phoneNumber:kt,phoneCode:Rt,password:Ut,firstAndLastNames:Et,qrCode:Dt,onError:Bt,initialMethod:"iOS"===s||"Android"===s?"phoneNumber":"qrCode"})}catch(e){if(console.error(e),"Disconnect"!==e.message)return void Qt({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}Mt(Tt("authorizationStateReady")),tn(c.getSessionData()),Qt({"@type":"updateApiReady"}),ln()}catch(e){throw e}}(mo,t)}const go=function(e,t){let n,s=!1;return function(){for(var a=arguments.length,i=new Array(a),o=0;o{s=!1,t(...n)})))}}((function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];d?t?u.push(e):d.push(e):(d=t?[]:[e],u=t?[e]:[],Promise.resolve().then((()=>{const e=d,t=u;d=void 0,u=void 0,t.forEach((e=>e())),e.forEach((e=>e()))})))}),(function(e){if(!ho||e!==fo)return;const t=ho;ho=void 0,t.forEach(lo)}));let po,fo,ho;function mo(e){ho?ho.push(e):ho=[e],po&&!o.has(e["@type"])||(po=function(e,t){let n,s,a,i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function(){s=!0;for(var o=arguments.length,r=new Array(o),c=0;c{if(!s)return self.clearInterval(n),void(n=void 0);s=!1,e(...a)}),t))}}(go,i,!0),fo=Math.random()),po(fo)}self.onerror=e=>{console.error(e),bo({type:"unhandledError",error:{message:e.error.message||"Uncaught exception in worker"}})},self.addEventListener("unhandledrejection",(e=>{console.error(e),bo({type:"unhandledError",error:{message:e.reason.message||"Uncaught rejection in worker"}})}));const _o=new Map;function yo(e){bo({type:"update",update:e})}function bo(e,t){t?postMessage(e,[t]):postMessage(e)}onmessage=async e=>{const{data:t}=e;switch(t.type){case"initApi":await uo(yo,t.args[0]);break;case"callMethod":{const{messageId:e,name:n,args:s}=t;try{if(e){const t=function(){for(var t=arguments.length,n=new Array(t),s=0;s1?t-1:0),s=1;s{var s=n(8764).Buffer;const a=n(4736),i=n(6842);function o(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],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){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;const n=a(e),i=[];for(let e=0;e2&&void 0!==arguments[2])||arguments[2],i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const o=(e=a(e)).bitLength(),r=Math.ceil(o/8);if(t0&&void 0!==arguments[0])||arguments[0];return o(l(8),!0,e)},mod:function(e,t){return(e%t+t)%t},crc32:function(e){u||(u=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},generateRandomBytes:l,generateKeyDataFromNonce:async function(e,t){e=r(e,16),t=r(t,32);const[n,a,i]=await Promise.all([d(s.concat([t,e])),d(s.concat([e,t])),d(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:d,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){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[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:l,modExp:d,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=d(a(b),t,g);if(m(n,g)){const e=h(n),i=o(await c(s.concat([e,A])),!1);if(i.greater(a(0)))return[t,e,i]}}})(),E=l(w.subtract(M),g);if(!m(E,g))throw new Error("bad gB");const D=U.multiply(v),B=k.add(D),T=d(E,B,g),[x,V,N,F,L]=await Promise.all([c(h(T)),c(I),c(C),c(n.salt1),c(n.salt2)]),q=await c(s.concat([_(V,N),F,L,R,A,x]));return new i.InputCheckPasswordSRP({srpId:e.srpId,A:s.from(R),M1:q})},computeDigest:async function(e,t){try{p(e.p,e.g)}catch(e){throw new Error("bad p/g in password")}return h(d(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){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],s=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];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){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[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:()=>d});var s=n(7150),a=n.n(s),i=n(9618),o=n(9674),r=n(7873),c=n.n(r),l=n(8764).Buffer;async function d(e,t){let{isCheckPassword:n,currentPassword:s,newPassword:r,hint:d="",email:u,emailCodeCallback:g,onEmailCodeError:p}=t;if(!r&&!s)throw new Error("Neither `currentPassword` nor `newPassword` is present");if(u&&(!g||!p))throw new Error("`email` present without `emailCodeCallback` and `onEmailCodeError`");const f=await e.invoke(new(a().account.GetPassword));f.newAlgo instanceof a().PasswordKdfAlgoUnknown||(f.newAlgo.salt1=l.concat([f.newAlgo.salt1,(0,i.generateRandomBytes)(32)])),!f.hasPassword&&s&&(s=void 0);const h=s?await(0,o.computeCheck)(f,s):new(a().InputCheckPasswordEmpty);if(n)await e.invoke(new(a().auth.CheckPassword)({password:h}));else try{await e.invoke(new(a().account.UpdatePasswordSettings)({password:h,newSettings:new(a().account.PasswordInputSettings)({newAlgo:f.newAlgo,newPasswordHash:r?await(0,o.computeDigest)(f.newAlgo,r):l.alloc(0),hint:d,email:u,newSecureSettings:void 0})}))}catch(t){if(!(t instanceof c().EmailUnconfirmedError))throw t;for(;;)try{const n=await g(t.codeLength);if(!n)throw new Error("Code is empty");await e.invoke(new(a().account.ConfirmPasswordEmail)({code:n}));break}catch(e){p(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),l=n(9618),d=n(8960),u=n(9270),{LAYER:g}=n(845),{constructors:p,requests:f}=n(7404),{ConnectionTCPObfuscated:h,MTProtoSender:m,UpdateConnectionState:_}=n(8415),{authFlow:y,checkAuthorization:b}=n(1545),{downloadFile:w}=n(2288),{uploadFile:v}=n(4766),{updateTwoFaSettings:I}=n(243),C=131072,A=["w","y","d","x","c","m","b","a","s"];class S{constructor(e,t,n){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:S.DEFAULT_OPTIONS;if(!t||!n)throw Error('Your API ID or Hash are invalid. Please read "Requirements" on README.md');const o={...S.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._isSwitchingDc=!1,this._destroyed=!1}async connect(){await this._initSession(),void 0===this._sender&&(this._sender=new m(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.isReconnecting=!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._isSwitchingDc=!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(){let e;for(;!this._destroyed;)if(await l.sleep(3e3),this._sender.isReconnecting||this._isSwitchingDc)e=void 0;else{try{const t=()=>this._sender.send(new f.PingDelayDisconnect({pingId:l.getRandomInt(Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER),disconnectDelay:6e4})),n=Date.now(),s=e?n-e:void 0;if(!s||s<5e3)await U((()=>R(t,5e3)),3,100);else{let e=setTimeout((()=>{this._handleUpdate(new _(_.disconnected)),e=void 0}),1e3);await R(t,3e3),e&&(clearTimeout(e),e=void 0),this._handleUpdate(new _(_.connected))}e=Date.now()}catch(t){if(console.warn(t),e=void 0,this._sender.isReconnecting||this._isSwitchingDc)continue;await this.disconnect(),await this.connect()}if((new Date).getTime()-this._lastRequest>18e5){try{await this.invoke(new f.updates.GetState)}catch(e){}e=void 0}}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=d.getDC(e);return this.session.setDC(e,t.ipAddress,t.port),await this._sender.authKey.setKey(void 0),this.session.setAuthKey(void 0),this._isSwitchingDc=!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=d.getDC(t,Boolean(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 l.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 l.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 m(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){return w(this,e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}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){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[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:d.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=A.indexOf(t);se.type===A[s])),n)return n}_downloadCachedPhotoSize(e){let t;return t=e instanceof p.PhotoStrippedSize?d.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:C}),a=await this._borrowExportedSender(4),i=await a.send(s);if(n+=131072,!i.bytes.length)break;if(t.push(i.bytes),i.bytes.length0&&void 0!==arguments[0]?arguments[0]:{update:void 0,others:void 0,channelId:void 0,ptsDate:void 0};for(const[t,n]of this._eventBuilders){const s=t.build(e.update);s&&await n(s)}}isConnected(){return!(!this._sender||!this._sender.isConnected())}}var P,M,k;function R(e,t){return Promise.race([e(),l.sleep(t).then((()=>Promise.reject(new Error("TIMEOUT"))))])}async function U(e,t,n){for(let s=0;s{"use strict";n.r(t),n.d(t,{authFlow:()=>d,checkAuthorization:()=>u});var s=n(7150),a=n.n(s),i=n(8960),o=n.n(i),r=n(9618),c=n(9674);const l="phoneNumber";async function d(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=l}=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,l=!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 d=await e.invoke(new(a().auth.SignIn)({phoneNumber:s,phoneCodeHash:i,phoneCode:o}));if(d instanceof a().auth.AuthorizationSignUpRequired){l=!0,c=d.termsOfService;break}return d.user}catch(t){if("SESSION_PASSWORD_NEEDED"===t.message)return h(e,0,n);n.onError(t)}if(l)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){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];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),l=n(8764).Buffer;function d(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,d(this,"deferred",void 0),d(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:d,workers:p=1}=n,{dcId:f,progressCallback:h,start:m=0}=n;r=r&&r{for(;;){let l;try{l=await e.getSender(f);const o=await l.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");C+=1/y,h(C)}return!r&&o.bytes.lengthr)break}const A=(await Promise.all(w)).filter(Boolean),S=r?r+1-m:void 0;return l.concat(A,S)}},4766:(e,t,n)=>{"use strict";n.r(t),n.d(t,{uploadFile:()=>d});var s=n(7150),a=n.n(s),i=n(9618),o=n(8960),r=n(7873),c=n.n(r),l=n(8764).Buffer;async function d(e,t){const{file:n,onProgress:s}=t;let{workers:r}=t;const{name:d,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=l.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:d}):new(a().InputFile)({id:g,parts:h,name:d,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:l}=n(9618);class d{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 d)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 l(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)])]),l=(await a(c)).slice(4,20);return r(l,!0,!0)}equals(e){return e instanceof this.constructor&&this._key&&e.getKey()&&e.getKey().equals(this._key)}}e.exports=d},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,l=s.one,d=s.one,u=s.zero,g=s.zero;for(;c.eq(s.one);){u=t;for(let i=0;s(i).lesser(l);i++)t=a(t,s(2),e).add(n).remainder(e);for(r=s.zero;r.lesser(l)&&c.eq(s.one);){g=t;const p=s.min(o,l.minus(r));for(let i=0;s(i).lesser(p);i++)t=a(t,s(2),e).add(n).remainder(e),d=d.multiply(u.minus(t).abs()).remainder(e);c=i.gcd(d,e),r=r.add(o)}l=l.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 d=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;el,ab2iBig:()=>o,ab2iLow:()=>i,i2ab:()=>c,i2abBig:()=>a,i2abLow:()=>s,isBigEndian:()=>r});const r=1===new Uint8Array(new Uint32Array([16909060]))[0],c=r?a:s,l=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 l{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;n2&&void 0!==arguments[2]?arguments[2]:e;for(let s=0;sa,s2i:()=>s,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(){for(var e=arguments.length,t=new Array(e),n=0;n{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){let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;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(){super(...arguments),t(this,"code",400),t(this,"message","BAD_REQUEST")}},UnauthorizedError:class extends n{constructor(){super(...arguments),t(this,"code",401),t(this,"message","UNAUTHORIZED")}},ForbiddenError:class extends n{constructor(){super(...arguments),t(this,"code",403),t(this,"message","FORBIDDEN")}},NotFoundError:class extends n{constructor(){super(...arguments),t(this,"code",404),t(this,"message","NOT_FOUND")}},AuthKeyError:class extends n{constructor(){super(...arguments),t(this,"code",406),t(this,"message","AUTH_KEY")}},FloodError:class extends n{constructor(){super(...arguments),t(this,"code",420),t(this,"message","FLOOD")}},ServerError:class extends n{constructor(){super(...arguments),t(this,"code",500),t(this,"message","INTERNAL")}},TimedOutError:class extends n{constructor(){super(...arguments),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 l 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 d 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+)/,d],[/MSG_WAIT_(.*)/,u],[/PHONE_MIGRATE_(\d+)/,c],[/SLOWMODE_WAIT_(\d+)/,l],[/USER_MIGRATE_(\d+)/,r],[/NETWORK_MIGRATE_(\d+)/,f],[/EMAIL_UNCONFIRMED_(\d+)/,h]];e.exports={rpcErrorRe:m,FileMigrateError:p,FloodTestPhoneWaitError:g,FloodWaitError:d,PhoneMigrateError:c,SlowModeWaitError:l,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(663);e.exports=class extends s{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{types:void 0,func:void 0};super(),e.types?this.types=e.types:this.types=!0}build(e){return e}}},663:e=>{e.exports={EventBuilder:class{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{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(){let e;return e=arguments.length>0&&void 0!==arguments[0]&&!arguments[0]?this.stream.readUInt32LE(this.offset):this.stream.readInt32LE(this.offset),this.offset+=4,e}readLong(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this.readLargeInt(64,e)}readFloat(){return this.read(4).readFloatLE(0)}readDouble(){return this.read(8).readDoubleLE(0)}readLargeInt(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const n=this.read(Math.floor(e/8));return o(n,!0,t)}read(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-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){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];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),l=n(8960),d=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:l,errors:d,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}],l=new Map;c.forEach((e=>{let{fingerprint:t,...n}=e;l.set(t.toString(),n)}));var d=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),v=new(a().PQInnerData)({pq:h.getByteArray(r),p:y,q:b,nonce:o.nonce,serverNonce:o.serverNonce,newNonce:w}).getBytes();if(v.length>144)throw new i.SecurityError("Step 1 invalid nonce from server");let I,C;for(const e of o.serverPublicKeyFingerprints)if(C=l.get(e.toString()),void 0!==C){I=e;break}if(void 0===I||void 0===C)throw new i.SecurityError("Step 2 could not find a valid key for fingerprints");const A=h.generateRandomBytes(192-v.length),S=d.concat([v,A]),P=d.from(S).reverse();let M;for(let e=0;e<20;e++){const e=h.generateRandomBytes(32),n=await h.sha256(d.concat([e,S])),s=d.concat([P,n]),a=new g(e,d.alloc(32)).encryptIge(s),i=h.bufferXor(e,await h.sha256(a)),o=d.concat([i,a]),r=h.readBigIntFromBuffer(o,!1,!1);if(r.greaterOrEquals(C.n)){t.debug("Aes key greater than RSA. retrying");continue}const c=h.modExp(r,u(C.e),C.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),B=new m(D);B.read(20);const T=B.tgReadObject();if(!(T instanceof a().ServerDHInnerData))throw new Error(`Step 3 answer was ${T}`);if(T.nonce.neq(o.nonce))throw new i.SecurityError("Step 3 Invalid nonce in encrypted answer");if(T.serverNonce.neq(o.serverNonce))throw new i.SecurityError("Step 3 Invalid server nonce in encrypted answer");const x=h.readBigIntFromBuffer(T.dhPrime,!1,!1),V=h.readBigIntFromBuffer(T.gA,!1,!1),N=T.serverTime-Math.floor((new Date).getTime()/1e3),F=h.readBigIntFromBuffer(h.generateRandomBytes(256),!1,!1),L=h.modExp(u(T.g),F,x),q=h.modExp(V,F,x),O=new(a().ClientDHInnerData)({nonce:o.nonce,serverNonce:o.serverNonce,retryId:u.zero,gB:h.getByteArray(L,!1)}).getBytes(),H=d.concat([await h.sha1(O),O]),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(q));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),l=s.alloc(4);l.writeInt32LE(t.length,0);const d=s.concat([s.concat([s.alloc(8),i,l]),t]);if(await this._connection.send(d),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),l=n(2301),d=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(8744),{BadMessageError:v}=n(8187),{BadServerSalt:I,BadMsgNotification:C,MsgDetailedInfo:A,MsgNewDetailedInfo:S,NewSessionCreated:P,FutureSalts:M,MsgsStateReq:k,MsgResendReq:R,MsgsAllInfo:U}=n(7404).constructors,{SecurityError:E}=n(8187),{InvalidBufferError:D}=n(8187),{LogOut:B}=n(7404).requests.auth,{RPCMessageToError:T}=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.isReconnecting=!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={[l.CONSTRUCTOR_ID]:this._handleRPCResult.bind(this),[d.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),[C.CONSTRUCTOR_ID]:this._handleBadNotification.bind(this),[A.CONSTRUCTOR_ID]:this._handleDetailedInfo.bind(this),[S.CONSTRUCTOR_ID]:this._handleNewDetailedInfo.bind(this),[P.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.userDisconnected=!1,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.isReconnecting}`);const e=await this._send_queue.get();if(this.isReconnecting)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.isReconnecting;){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=T(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 v(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 B&&(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.isReconnecting&&(this.isReconnecting=!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.isReconnecting=!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:l}=n(2058),{SecurityError:d,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 l=s.alloc(4);l.writeInt32LE(o,0);const d=s.alloc(4);d.writeInt32LE(r.length,0);const u=p(i,8);return e.write(s.concat([u,l,d])),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:l}=await this._calcKey(this.authKey.getKey(),r,!0),d=i.readBufferFromBigInt(this.authKey.keyId,8);return s.concat([d,r,new o(l,c).encryptIge(s.concat([e,a]))])}async decryptMessageData(e){if(e.length<8)throw new u(e);if(e.length<0)throw new d("Server replied with negative length");if(e.length%4!=0)throw new d("Server replied with length not divisible by 4");if(i.readBigIntFromBuffer(e.slice(0,8)).neq(this.authKey.keyId))throw new d("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 d("Received msg_key doesn't match with expected one");const g=new r(e);if(g.readLong(),!g.readLong().eq(this.id))throw new d("Server replied with a wrong session ID");const p=g.readLong();if(this.msgIds.includes(p.toString()))throw new d("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 d("Server replied with the wrong message padding");const _=g.tgReadObject();return new l(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){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};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(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];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(){super(...arguments),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 l extends c{constructor(e){super(e),this.tag=l.tag,this.obfuscateTag=l.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(l,"tag",s.from("ef","hex")),a(l,"obfuscateTag",s.from("efefefef","hex")),e.exports={ConnectionTCPAbridged:class extends r{constructor(){super(...arguments),a(this,"PacketCodecClass",l)}},AbridgedPacketCodec:l}},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 l{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)),l=s.from(a.slice(0,32)),d=s.from(a.slice(32,48)),u=new c(o,r),g=new c(l,d);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(){super(...arguments),a(this,"ObfuscatedIO",l),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)=>{const s=n(5585),a=n(4046),{Connection:i,ConnectionTCPFull:o,ConnectionTCPAbridged:r,ConnectionTCPObfuscated:c}=n(417),{UpdateConnectionState:l,UpdateServerTimeOffset:d}=n(8744);e.exports={Connection:i,ConnectionTCPFull:o,ConnectionTCPAbridged:r,ConnectionTCPObfuscated:c,MTProtoPlainSender:s,MTProtoSender:a,UpdateConnectionState:l,UpdateServerTimeOffset:d}},8744: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){this.state=e,this.origin=t}}t(n,"disconnected",-1),t(n,"connected",1),t(n,"broken",0),e.exports={UpdateConnectionState:n,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){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];this._dcId=e,this._serverAddress=t,this._port=n,delete this._authKeys[e],s||this._onUpdate()}getAuthKey(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this._dcId;return this._authKeys[e]}setAuthKey(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]: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(4678),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){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];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(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this._dcId;return this._authKeys[e]}setAuthKey(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]: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(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:void 0;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:139,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),l=n(4779),d=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":case"bytes":return o(e);case"Bool":return e?s.from("b5757299","hex"):s.from("379779bc","hex");case"true":return s.alloc(0);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#a8edd0f5 flags:# pinned:flags.2?true unread_mark:flags.3?true peer:Peer top_message:int read_inbox_max_id:int read_outbox_max_id:int unread_count:int unread_mentions_count:int unread_reactions_count:int notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?int = Dialog;\ndialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog;\nphotoEmpty#2331b22d id:long = Photo;\nphoto#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector 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;\ninputReportReasonIllegalDrugs#a8eb2be = ReportReason;\ninputReportReasonPersonalDetails#9ec7863d = 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 videos:flags.6?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 rtmp_stream:flags.12?true listeners_hidden:flags.13?true id:long access_hash:long participants_count:int title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int unmuted_video_count:flags.10?int unmuted_video_limit:int version:int = GroupCall;\ninputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall;\ngroupCallParticipant#eba636fe flags:# muted:flags.0?true left:flags.1?true can_self_unmute:flags.2?true just_joined:flags.4?true versioned:flags.5?true min:flags.8?true muted_by_you:flags.9?true volume_by_admin:flags.10?true self:flags.12?true video_joined:flags.15?true peer:Peer date:int active_date:flags.3?int source:int volume:flags.7?int about:flags.11?string raise_hand_rating:flags.13?long video:flags.6?GroupCallParticipantVideo presentation:flags.14?GroupCallParticipantVideo = GroupCallParticipant;\nphone.groupCall#9e727aad call:GroupCall participants:Vector 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#4f2b9479 flags:# min:flags.0?true can_see_list:flags.2?true results:Vector recent_reactions:flags.1?Vector = MessageReactions;\nmessages.messageReactionsList#31bd492d flags:# count:int reactions:Vector chats:Vector users:Vector next_offset:flags.0?string = messages.MessageReactionsList;\navailableReaction#c077ec01 flags:# inactive:flags.0?true reaction:string title:string static_icon:Document appear_animation:Document select_animation:Document activate_animation:Document effect_animation:Document around_animation:flags.1?Document center_icon:flags.1?Document = AvailableReaction;\nmessages.availableReactionsNotModified#9f071957 = messages.AvailableReactions;\nmessages.availableReactions#768e3aad hash:int reactions:Vector = messages.AvailableReactions;\nmessages.translateNoResult#67ca4737 = messages.TranslatedText;\nmessages.translateResultText#a214f7d0 text:string = messages.TranslatedText;\nmessagePeerReaction#51b67eff flags:# big:flags.0?true unread:flags.1?true peer_id:Peer reaction:string = MessagePeerReaction;\ngroupCallStreamChannel#80eb48af channel:int scale:int last_timestamp_ms:long = GroupCallStreamChannel;\nphone.groupCallStreamChannels#d0e482b2 channels:Vector = phone.GroupCallStreamChannels;\nphone.groupCallStreamRtmpUrl#2dbf3432 url:string key:string = phone.GroupCallStreamRtmpUrl;\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;\ncontacts.resolvePhone#8af94344 phone:string = contacts.ResolvedPeer;\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.reportSpam#cf1592db peer:InputPeer = Bool;\nmessages.getPeerSettings#efd9a6a2 peer:InputPeer = messages.PeerSettings;\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.saveGif#327a30cb id:InputDocument unsave:Bool = Bool;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\nmessages.sendInlineBotResult#7aa11297 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true hide_via:flags.11?true peer:InputPeer reply_to_msg_id:flags.0?int random_id:long query_id:long id:string schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.editMessage#48f71778 flags:# no_webpage:flags.1?true peer:InputPeer id:int message:flags.11?string media:flags.14?InputMedia reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector 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.hidePeerSettingsBar#4facb138 peer:InputPeer = Bool;\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.getExportedChatInvites#a2b5a3f6 flags:# revoked:flags.3?true peer:InputPeer admin_id:InputUser offset_date:flags.2?int offset_link:flags.2?string limit:int = messages.ExportedChatInvites;\nmessages.editExportedChatInvite#bdca2f75 flags:# revoked:flags.2?true peer:InputPeer link:string expire_date:flags.0?int usage_limit:flags.1?int request_needed:flags.3?Bool title:flags.4?string = messages.ExportedChatInvite;\nmessages.deleteRevokedExportedChatInvites#56987bd5 peer:InputPeer admin_id:InputUser = Bool;\nmessages.deleteExportedChatInvite#d464a42b peer:InputPeer link:string = Bool;\nmessages.getChatInviteImporters#df04dd4e flags:# requested:flags.0?true peer:InputPeer link:flags.1?string q:flags.2?string offset_date:int offset_user:InputUser limit:int = messages.ChatInviteImporters;\nmessages.getMessageReadParticipants#2c6f97b7 peer:InputPeer msg_id:int = Vector;\nmessages.hideChatJoinRequest#7fe7e815 flags:# approved:flags.0?true peer:InputPeer user_id:InputUser = Updates;\nmessages.hideAllChatJoinRequests#e085f4ea flags:# approved:flags.0?true peer:InputPeer link:flags.1?string = Updates;\nmessages.toggleNoForwards#b11eafa2 peer:InputPeer enabled:Bool = Updates;\nmessages.saveDefaultSendAs#ccfddf96 peer:InputPeer send_as:InputPeer = Bool;\nmessages.sendReaction#25690ce4 flags:# big:flags.1?true peer:InputPeer msg_id:int reaction:flags.0?string = Updates;\nmessages.getMessagesReactions#8bba90e6 peer:InputPeer id:Vector = Updates;\nmessages.getMessageReactionsList#e0ee6b77 flags:# peer:InputPeer id:int reaction:flags.0?string offset:flags.1?string limit:int = messages.MessageReactionsList;\nmessages.setChatAvailableReactions#14050ea6 peer:InputPeer available_reactions:Vector = Updates;\nmessages.getAvailableReactions#18dea0ac hash:int = messages.AvailableReactions;\nmessages.setDefaultReaction#d960c4d4 reaction:string = 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.getAppConfig#98914110 = JSONValue;\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:# rtmp_stream:flags.2?true peer:InputPeer random_id:int title:flags.0?string schedule_date:flags.1?int = Updates;\nphone.joinGroupCall#b132ff7b flags:# muted:flags.0?true video_stopped:flags.2?true call:InputGroupCall join_as:InputPeer invite_hash:flags.1?string params:DataJSON = Updates;\nphone.leaveGroupCall#500377f9 call:InputGroupCall source:int = Updates;\nphone.discardGroupCall#7a777135 call:InputGroupCall = Updates;\nphone.getGroupCall#41845db call:InputGroupCall limit:int = phone.GroupCall;\nphone.getGroupParticipants#c558d8ab call:InputGroupCall ids:Vector 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;\nstats.getBroadcastStats#ab42441a flags:# dark:flags.0?true channel:InputChannel = stats.BroadcastStats;\nstats.loadAsyncGraph#621d5fa0 flags:# token:string x:flags.0?long = StatsGraph;\nstats.getMegagroupStats#dcdf8607 flags:# dark:flags.0?true channel:InputChannel = stats.MegagroupStats;"},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 l(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 d=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];e.flags.includes("g")||(e=new RegExp(e.source,"g"));const s=e.exec(t);return s&&(n.push(s.slice(1)),d(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=d(/({)?(\w+):([\w\d<>#.?!]+)}?/,e),r={name:n[1],constructorId:parseInt(n[2],16),argsConfig:{},subclassOfId:l(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=l(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:d,parseTl:function*(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:o;(n||[]).reduce(((e,t)=>({...e,[t.name]:t})),{});const a=[],i={},c={},l=e;let d=!1;for(let e of l.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;d="functions"===e}else try{const t=u(e,d);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,[802,313],(()=>a(1742)));return a.O(e)},e=[],a.O=(t,n,s,i)=>{if(!n){var o=1/0;for(d=0;d=i)&&Object.keys(a.O).every((e=>a.O[e](n[c])))?n.splice(c--,1):(r=!1,i0&&e[d-1][2]>i;d--)e[d]=e[d-1];e[d]=[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+"."+{313:"5cd1718104a79212da23",802:"acd83f1b28a8893b9dba"}[e]+".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={742: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=()=>Promise.all([a.e(802),a.e(313)]).then(t),a.x()})(); -//# sourceMappingURL=742.e09d8d2bec0ce4cf0543.js.map \ No newline at end of file +(()=>{var e,t,n={1742:(e,t,n)=>{"use strict";var s={};n.r(s),n.d(s,{Type:()=>Gt,clear:()=>Wt,fetch:()=>Kt,save:()=>zt});var a={};n.r(a),n.d(a,{addChatMembers:()=>Zn,answerCallbackButton:()=>Ki,blockContact:()=>vi,checkChatUsername:()=>Ia,checkPassword:()=>Oa,checkUsername:()=>fi,clearDraft:()=>wn,clearPassword:()=>Ha,createChannel:()=>In,createGroupCall:()=>ti,createGroupChat:()=>kn,deleteChannel:()=>Mn,deleteChat:()=>Sn,deleteChatFolder:()=>xn,deleteChatMember:()=>Yn,deleteChatUser:()=>An,deleteContact:()=>ea,deleteExportedChatInvite:()=>ka,deleteHistory:()=>ws,deleteMessages:()=>ys,deleteRevokedExportedChatInvites:()=>Ra,deleteScheduledMessages:()=>bs,destroy:()=>Yt,discardGroupCall:()=>$a,disconnect:()=>en,downloadMedia:()=>on,editChatFolder:()=>Tn,editChatPhoto:()=>Rn,editExportedChatInvite:()=>Pa,editGroupCallParticipant:()=>Ja,editGroupCallTitle:()=>Qa,editMessage:()=>ps,exportChatInvite:()=>Ma,exportGroupCallInvite:()=>Xa,faveSticker:()=>ca,fetchAnimatedEmojiEffects:()=>ua,fetchAnimatedEmojis:()=>da,fetchAppConfig:()=>qi,fetchAuthorizations:()=>Ci,fetchBlockedContacts:()=>wi,fetchChannelStatistics:()=>oo,fetchChat:()=>_n,fetchChatFolders:()=>Dn,fetchChatInviteImporters:()=>Ua,fetchChatSettings:()=>hn,fetchChats:()=>pn,fetchCommonChats:()=>js,fetchContactList:()=>Qs,fetchContentSettings:()=>Fi,fetchCountryList:()=>Hi,fetchCurrentUser:()=>ln,fetchEmojiKeywords:()=>ba,fetchExportedChatInvites:()=>Sa,fetchFavoriteStickers:()=>oa,fetchFeaturedStickers:()=>ra,fetchFullChat:()=>fn,fetchFullUser:()=>Ws,fetchGroupCallParticipants:()=>Za,fetchGroupStatistics:()=>ro,fetchGroupsForDiscussion:()=>$n,fetchInlineBot:()=>Wi,fetchInlineBotResults:()=>ji,fetchLangPack:()=>Ei,fetchLangStrings:()=>Di,fetchLanguages:()=>Ui,fetchMembers:()=>jn,fetchMessage:()=>ls,fetchMessageReactions:()=>eo,fetchMessageReactionsList:()=>to,fetchMessages:()=>cs,fetchNearestCountry:()=>$s,fetchNotificationExceptions:()=>Pi,fetchNotificationSettings:()=>Mi,fetchPinnedMessages:()=>Vs,fetchPrivacySettings:()=>Bi,fetchProfilePhotos:()=>ta,fetchRecentStickers:()=>ia,fetchRecommendedChatFolders:()=>Bn,fetchSavedGifs:()=>pa,fetchScheduledHistory:()=>Bs,fetchSeenBy:()=>Ns,fetchSendAs:()=>Fs,fetchSponsoredMessages:()=>qs,fetchStatisticsAsyncGraph:()=>co,fetchStickerSets:()=>aa,fetchStickers:()=>la,fetchStickersForEmoji:()=>ya,fetchTopInlineBots:()=>zi,fetchTopUsers:()=>Js,fetchUsers:()=>Xs,fetchWallpapers:()=>yi,fetchWebPagePreview:()=>ks,findFirstMessageIdAfterDate:()=>Ds,forwardMessages:()=>Es,getAvailableReactions:()=>Zi,getChatByPhoneNumber:()=>Nn,getChatByUsername:()=>Fn,getGroupCall:()=>ja,getPasswordInfo:()=>La,getPaymentForm:()=>ci,getReceipt:()=>li,hideAllChatJoinRequests:()=>Da,hideChatJoinRequest:()=>Ea,hideChatReportPanel:()=>Ba,importChatInvite:()=>ns,importContact:()=>Zs,installStickerSet:()=>ha,joinChannel:()=>Cn,joinGroupCall:()=>ei,joinGroupCallPresentation:()=>ni,leaveChannel:()=>Pn,leaveGroupCall:()=>Ya,leaveGroupCallPresentation:()=>ai,loadPollOptionResults:()=>Us,markMessageListRead:()=>Cs,markMessagesRead:()=>As,migrateChat:()=>Qn,openChatByInvite:()=>Xn,pinMessage:()=>ms,provideAuthCode:()=>Vt,provideAuthPassword:()=>Nt,provideAuthPhoneNumber:()=>xt,provideAuthRegistration:()=>Ft,provideRecoveryEmailCode:()=>za,registerDevice:()=>Ti,reportMessages:()=>vs,reportSpam:()=>na,requestChatUpdate:()=>yn,requestThreadInfoUpdate:()=>Ss,rescheduleMessage:()=>fs,restartAuth:()=>Lt,restartAuthWithQr:()=>qt,saveDefaultSendAs:()=>Ls,saveDraft:()=>bn,saveGif:()=>fa,searchChats:()=>mn,searchGifs:()=>_a,searchMessagesGlobal:()=>Ms,searchMessagesLocal:()=>Ps,searchStickers:()=>ga,sendEmojiInteraction:()=>Xi,sendInlineBotResult:()=>$i,sendMessage:()=>us,sendMessageAction:()=>Is,sendPaymentForm:()=>ri,sendPollVote:()=>Rs,sendReaction:()=>Yi,sendScheduledMessages:()=>Ts,sendWatchingEmojiInteraction:()=>Qi,setChatEnabledReactions:()=>ss,setChatUsername:()=>Ca,setDefaultReaction:()=>no,setDiscussionGroup:()=>Jn,setPrivacySettings:()=>Vi,startBot:()=>Ji,terminateAllAuthorizations:()=>Si,terminateAuthorization:()=>Ai,toggleChatArchived:()=>En,toggleChatPinned:()=>Un,toggleDialogUnread:()=>Vn,toggleGroupCallStartSubscription:()=>si,toggleIsProtected:()=>as,togglePreHistoryHidden:()=>qn,toggleSignatures:()=>Wn,unblockContact:()=>Ii,uninstallStickerSet:()=>ma,unpinAllMessages:()=>_s,unregisterDevice:()=>xi,updateChatAbout:()=>zn,updateChatAdmin:()=>Gn,updateChatDefaultBannedRights:()=>On,updateChatMemberBannedRights:()=>Hn,updateChatMutedState:()=>vn,updateChatTitle:()=>Kn,updateContact:()=>Ys,updateContactSignUpNotification:()=>ki,updateContentSettings:()=>Li,updateIsOnline:()=>Ni,updateNotificationSettings:()=>Ri,updatePassword:()=>Ga,updatePrivateLink:()=>Aa,updateProfile:()=>pi,updateProfilePhoto:()=>mi,updateRecoveryEmail:()=>Ka,updateUsername:()=>hi,uploadProfilePhoto:()=>_i,uploadWallpaper:()=>bi,validateRequestedInfo:()=>oi,viewSponsoredMessage:()=>Os});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"]),l=(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 d,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){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"image/jpeg";const s=t?"":`data:${n};base64,`;return`${s}${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 v(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 C={localMessages:{},chats:{},users:{},messages:{},documents:{},stickerSets:{},photos:{},webDocuments:{}},A="application/x-tgsticker",S="video/webm";function P(e){if(e instanceof g.Api.DocumentEmpty)return;const{mimeType:t}=e,n=e.attributes.find((e=>e instanceof g.Api.DocumentAttributeSticker)),s=(t===A||t===S)&&e.attributes.find((e=>e instanceof g.Api.DocumentAttributeFilename));if(!n&&!s)return;const a=t===A,i=t===S,o=e.attributes.find((e=>e instanceof g.Api.DocumentAttributeImageSize)),r=e.attributes.find((e=>e instanceof g.Api.DocumentAttributeVideo)),c=o||r,l=n&&n.stickerset instanceof g.Api.InputStickerSetID?n.stickerset:void 0,d=null==n?void 0:n.alt,u=e.thumbs&&e.thumbs.find((e=>e instanceof g.Api.PhotoCachedSize));if(!(t!==S||self.isWebmSupported||u||e.thumbs&&e.thumbs.find((e=>e instanceof g.Api.PhotoSize))))return;const p=e.thumbs&&e.thumbs.find((e=>e instanceof g.Api.PhotoPathSize)),f=u?function(e){const{w:t,h:n,bytes:s}=e;return{dataUri:m(s,void 0,"image/webp"),width:t,height:n}}(u):p&&c?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}}(p,c):void 0,{w:h,h:_}=u||c||{};return{id:String(e.id),stickerSetId:l?String(l.id):"NO_STICKER_SET",stickerSetAccessHash:l&&String(l.accessHash),emoji:d,isLottie:a,isVideo:i,width:h,height:_,thumbnail:f}}function M(e){const{archived:t,animated:n,installedDate:s,videos:a,id:i,accessHash:o,title:r,thumbs:c,count:l,shortName:d}=e;return{archived:t,isLottie:n,isVideos:a,installedDate:s,id:String(i),accessHash:String(o),title:r,hasThumbnail:Boolean(null==c?void 0:c.length),count:l,shortName:d}}function k(e){const t=M(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=P(e);n&&(t.covers.push(n),C.documents[String(e.id)]=e)}})),t}function R(e,t){let n=0;const s=new Array(t),a=e.length/t,i=e[0],o=e[e.length-1];for(let d=0;d1&&void 0!==arguments[1]&&arguments[1];const n=N(e.id,"user");!t&&C.users[n]||(C.users[n]=e)}function K(e){e.forEach((e=>{e instanceof g.Api.User&&e.photo?G(e):(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&e.photo&&function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=N(e.id,e instanceof g.Api.Chat?"chat":"channel");t&&C.chats[n]||(C.chats[n]=e)}(e)}))}function z(e){return String.fromCharCode(...e)}function W(e){return L.from(e,"binary")}function j(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 $(e){const t=j(e);return"user"===t?new g.Api.PeerUser({userId:ue(e,"user")}):"channel"===t?new g.Api.PeerChannel({channelId:ue(e,"channel")}):new g.Api.PeerChat({chatId:ue(e,"chat")})}function J(e,t){const n=j(e);return"user"===n?new g.Api.InputPeerUser({userId:ue(e,"user"),accessHash:E()(t)}):"channel"===n?new g.Api.InputPeerChannel({channelId:ue(e,"channel"),accessHash:E()(t)}):new g.Api.InputPeerChat({chatId:ue(e,"chat")})}function Q(e){const t=j(e);let n;var s;if("user"===t){if(n=null===(s=C.users[e])||void 0===s?void 0:s.accessHash,!n)return}else if("channel"===t){var a;if(n=null===(a=C.chats[e])||void 0===a?void 0:a.accessHash,!n)return}return J(e,String(n))}function X(e,t){const n=j(e);return"user"===n?new g.Api.InputUser({userId:ue(e,"user"),accessHash:E()(t)}):"channel"===n?new g.Api.InputChannel({channelId:ue(e,"channel"),accessHash:E()(t)}):ue(e,"chat")}function Z(e,t){return new g.Api.InputStickerSetID({id:E()(e),accessHash:E()(t)})}function Y(e){const t=C.documents[e.id];if(t)return new g.Api.InputDocument(f(t,["id","accessHash","fileReference"]))}function ee(e){const t=Y(e);if(t)return new g.Api.InputMediaDocument({id:t})}function te(){return(0,D.readBigIntFromBuffer)((0,D.generateRandomBytes)(8),!0,!0)}function ne(e,t,n){return new g.Api.Message({id:e,peerId:$(t),fromId:$(t),media:n.media})}function se(e){const{type:t,offset:n,length:s,url:a,userId:i}=e,o=i?C.users[i]:void 0;switch(t){case B.Bold:return new g.Api.MessageEntityBold({offset:n,length:s});case B.Italic:return new g.Api.MessageEntityItalic({offset:n,length:s});case B.Underline:return new g.Api.MessageEntityUnderline({offset:n,length:s});case B.Strike:return new g.Api.MessageEntityStrike({offset:n,length:s});case B.Code:return new g.Api.MessageEntityCode({offset:n,length:s});case B.Pre:return new g.Api.MessageEntityPre({offset:n,length:s,language:""});case B.Blockquote:return new g.Api.MessageEntityBlockquote({offset:n,length:s});case B.TextUrl:return new g.Api.MessageEntityTextUrl({offset:n,length:s,url:a});case B.Url:return new g.Api.MessageEntityUrl({offset:n,length:s});case B.Hashtag:return new g.Api.MessageEntityHashtag({offset:n,length:s});case B.MentionName:return new g.Api.InputMessageEntityMentionName({offset:n,length:s,userId:new g.Api.InputUser({userId:E()(i),accessHash:o.accessHash})});case B.Spoiler:return new g.Api.MessageEntitySpoiler({offset:n,length:s});default:return new g.Api.MessageEntityUnknown({offset:n,length:s})}}function ae(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 ie(e){let{phone:t,firstName:n,lastName:s}=e;return new g.Api.InputPhoneContact({clientId:E()(1),phone:t,firstName:n,lastName:s})}function oe(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return new g.Api.ChatBannedRights({...e,untilDate:t})}function re(e){return new g.Api.ChatAdminRights(e)}function ce(e){const{shippingAddress:t}=e;return new g.Api.PaymentRequestedInfo({...e,shippingAddress:t?new g.Api.PostAddress(t):void 0})}function le(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"illegalDrugs":return new g.Api.InputReportReasonIllegalDrugs;case"personalDetails":return new g.Api.InputReportReasonPersonalDetails;case"other":return new g.Api.InputReportReasonOther}}function ue(e,t){return"number"==typeof e?E()(Math.abs(e)):"user"===t?E()(e):E()(e.slice(1))}function ge(e){return new g.Api.InputGroupCall({id:E()(e.id),accessHash:E()(e.accessHash)})}const pe="temp";let fe,he=1e9;function me(e){const{fromId:t,message:n,entities:s,startParam:a,channelPost:i,chatInvite:o,chatInviteHash:r,randomId:c}=e,l=t?F(t):void 0,d=o?o instanceof g.Api.ChatInvite?o.title:o.chat instanceof g.Api.ChatEmpty?void 0:o.chat.title:void 0;return{randomId:z(c),isBot:!!t&&x(t),text:Ae(n,s),expiresAt:Math.round(Date.now()/1e3)+3e5,...l&&{chatId:l},...r&&{chatInviteHash:r},...o&&{chatInviteTitle:d},...a&&{startParam:a},...i&&{channelPostId:i}}}function _e(e){const t=q(e);if(t&&(e instanceof g.Api.Message||e instanceof g.Api.MessageService))return ye(t,e)}function ye(e,t){const n=t.fromId?F(t.fromId):void 0,s=t.peerId?F(t.peerId):void 0,a=!n&&e===fe,i=t.out&&!t.post||a&&!t.fwdFrom,o=Ce(t),r=t.action&&function(e,t,n,s,a){if(e instanceof g.Api.MessageActionEmpty)return;let i,o,r,c;const l=[];let d,u="other";const p="users"in e?e.users&&e.users.map((e=>N(e,"user"))):"userId"in e&&[N(e.userId,"user")]||[];let f;if(e instanceof g.Api.MessageActionChatCreate)c="Notification.CreatedChatWithTitle",l.push("%action_origin%",e.title),u="chatCreate";else if(e instanceof g.Api.MessageActionChatEditTitle)s?(c="Channel.MessageTitleUpdated",l.push(e.title)):(c="Notification.ChangedGroupName",l.push("%action_origin%",e.title));else if(e instanceof g.Api.MessageActionChatEditPhoto)s?c="Channel.MessagePhotoUpdated":(c="Notification.ChangedGroupPhoto",l.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",l.push("%target_user%")):(c="Notification.Invited",l.push("%action_origin%","%target_user%"));else if(e instanceof g.Api.MessageActionChatDeleteUser)!t||p.includes(t)?(c="Notification.LeftChat",l.push("%target_user%")):(c="Notification.Kicked",l.push("%action_origin%","%target_user%"));else if(e instanceof g.Api.MessageActionChatJoinedByLink)c="Notification.JoinedGroupByLink",l.push("%action_origin%");else if(e instanceof g.Api.MessageActionChannelCreate)c="Notification.CreatedChannel";else if(e instanceof g.Api.MessageActionChatMigrateTo)f=F(e),c="Migrated to %target_chat%",l.push("%target_chat%");else if(e instanceof g.Api.MessageActionChannelMigrateFrom)f=F(e),c="Migrated from %target_chat%",l.push("%target_chat%");else if(e instanceof g.Api.MessageActionPinMessage)c="Chat.Service.Group.UpdatedPinnedMessage1",l.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);l.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()},l.push("%action_origin%","%target_user%");else if(e instanceof g.Api.MessageActionContactSignUp)c="Notification.Joined",l.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),l.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",l.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",l.push(e.domain)):e instanceof g.Api.MessageActionCustomAction?c=e.message:e instanceof g.Api.MessageActionChatJoinedByRequest?(c="ChatService.UserJoinedGroupByRequest",l.push("%action_origin%")):c="ChatList.UnsupportedMessage";return"photo"in e&&e.photo instanceof g.Api.Photo&&(H(e.photo),d=v(e.photo)),{text:c,type:u,targetUserIds:p,targetChatId:f,photo:d,amount:o,currency:r,translationValues:l,call:i}}(t.action,n,s,Boolean(t.post),i);r&&(o.action=r);const{replyToMsgId:c,replyToTopId:l,replyToPeerId:d}=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((e=>{let{buttons:n}=e;return n.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=z(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){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=e.savedFromPeer&&F(e.savedFromPeer),s=e.fromId&&F(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),C=Boolean(I)&&!(o.document||o.audio||o.sticker),A=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&&fe||e,views:t.views,isFromScheduled:t.fromScheduled,reactions:t.reactions&&be(t.reactions),...c&&{replyToMessageId:c},...d&&{replyToChatId:F(d)},...l&&{replyToTopMessageId:l},..._&&{forwardInfo:_},...u&&{isEdited:u},...t.editDate&&{editDate:t.editDate},...b&&{isMediaUnread:b},...t.mentioned&&b&&{hasUnreadMention:!0},...t.mentioned&&{isMentioned:!0},...I&&{groupedId:I,isInAlbum:C},inlineButtons:p,...f&&{keyboardButtons:f,keyboardPlaceholder:h,isKeyboardSingleUse:m},...A&&{shouldHideKeyboardButtons:A},...t.viaBotId&&{viaBotId:N(t.viaBotId,"user")},...(null==y?void 0:y.comments)&&{threadInfo:Ne(y,t.id,e)},...w&&{adminTitle:w},...t.noforwards&&{isProtected:!0}}}function be(e){const{recentReactions:t,results:n,canSeeList:s}=e;return{canSeeList:s,results:n.map(we),recentReactions:null==t?void 0:t.map(ve)}}function we(e){const{chosen:t,count:n,reaction:s}=e;return{isChosen:t,count:n,reaction:s}}function ve(e){const{peerId:t,reaction:n}=e;return{userId:F(t),reaction:n}}function Ie(e){const{selectAnimation:t,staticIcon:n,reaction:s,title:a,inactive:i,aroundAnimation:o,centerIcon:r}=e;return{selectAnimation:ke(t),staticIcon:ke(n),aroundAnimation:o?ke(o):void 0,centerIcon:r?ke(r):void 0,reaction:s,title:a,isInactive:i}}function Ce(e){var t;let n={};return e.media&&(n={...Pe(e.media)}),!e.message||n.sticker||n.poll||n.contact||null!==(t=n.video)&&void 0!==t&&t.isRound||(n={...n,text:Ae(e.message,e.entities)}),n}function Ae(e,t){return{text:e,...t&&{entities:t.map(Ve)}}}function Se(e){if(e instanceof g.Api.DraftMessageEmpty)return;const{message:t,entities:n,replyToMsgId:s,date:a}=e;return{formattedText:t?Ae(t,n):void 0,replyingToId:s,date:a}}function Pe(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 P(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 v(e.photo)}(e);if(n)return{photo:n};const s=function(e){if(e instanceof g.Api.MessageMediaDocument&&e.document instanceof g.Api.Document&&e.document.mimeType.startsWith("video"))return Me(e.document)}(e);if(s)return{video:s};const a=function(e){if(!(e instanceof g.Api.MessageMediaDocument&&e.document&&e.document instanceof g.Api.Document))return;const t=e.document.attributes.find((e=>e instanceof g.Api.DocumentAttributeAudio));if(!t||t.voice)return;const n=e.document.thumbs&&e.document.thumbs.filter((e=>e instanceof g.Api.PhotoSize)).map((e=>I(e)));return{id:String(e.document.id),fileName:Be(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 ke(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:N(a,"user")}}(e);if(r)return{contact:r};const c=function(e){if(e instanceof g.Api.MessageMediaPoll)return Ue(e.poll,e.results)}(e);if(c)return{poll:c};const l=De(e);if(l)return{webPage:l};const d=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);if(d)return{invoice:d};const u=function(e){return e instanceof g.Api.MessageMediaGeo?function(e){const t=Re(e.geo);return t&&{type:"geo",geo:t}}(e):e instanceof g.Api.MessageMediaVenue?function(e){const{geo:t,title:n,provider:s,address:a,venueId:i,venueType:o}=e,r=Re(t);return r&&{type:"venue",geo:r,title:n,provider:s,address:a,venueId:i,venueType:o}}(e):e instanceof g.Api.MessageMediaGeoLive?function(e){const{geo:t,period:n,heading:s}=e,a=Re(t);return a&&{type:"geoLive",geo:a,period:n,heading:s}}(e):void 0}(e);return u?{location:u}:void 0}function Me(e){if(e instanceof g.Api.DocumentEmpty)return;const{id:t,mimeType:n,thumbs:s,size:a,attributes:i}=e;if("video/webm"===n&&!self.isWebmSupported)return;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:l,h:d,supportsStreaming:u=!1,roundMessage:p=!1}=o;return{id:String(t),mimeType:n,duration:c,fileName:Be(e,"video"),width:l,height:d,supportsStreaming:u,isRound:p,isGif:Boolean(r),thumbnail:w(s),size:a}}function ke(e){if(!(e instanceof g.Api.Document))return;const{id:t,size:n,mimeType:s,date:a,thumbs:i,attributes:o}=e,l=i&&w(i);let d,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)){d="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)&&(d="video");return{id:String(t),size:n,mimeType:s,timestamp:a,fileName:Be(e),thumbnail:l,mediaType:d,mediaSize:u}}function Re(e){if(e instanceof g.Api.GeoPointEmpty)return;const{long:t,lat:n,accuracyRadius:s,accessHash:a}=e;return{long:t,lat:n,accessHash:a.toString(),accuracyRadius:s}}function Ue(e,t){const{id:n,answers:s}=e,a=s.map((e=>({text:e.text,option:z(e.option)})));return{id:String(n),summary:{isPublic:e.publicVoters,...f(e,["closed","multipleChoice","quiz","question","closePeriod","closeDate"]),answers:a},results:Ee(t)}}function Ee(e){const{results:t,totalVoters:n,recentVoters:s,solution:a,solutionEntities:i}=e,o=t&&t.map((e=>{let{option:t,chosen:n,correct:s,voters:a}=e;return{isChosen:n,isCorrect:s,option:z(t),votersCount:a}}));return{totalVoters:n,recentVoterIds:null==s?void 0:s.map((e=>N(e,"user"))),results:o,solution:a,...i&&{solutionEntities:i.map(Ve)}}}function De(e){if(!(e instanceof g.Api.MessageMediaWebPage&&e.webpage instanceof g.Api.WebPage))return;const{id:t,photo:n,document:s}=e.webpage;let a;return s instanceof g.Api.Document&&s.mimeType.startsWith("video/")&&(a=Me(s)),{id:Number(t),...f(e.webpage,["url","displayUrl","type","siteName","title","description","duration"]),photo:n instanceof g.Api.Photo?v(n):void 0,document:!a&&s?ke(s):void 0,video:a}}function Be(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"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 Te(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:pe,sizes:[],thumbnail:{width:o,height:r,dataUri:""},blobUrl:n}}:{video:{id:pe,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}=R(n,63);return{voice:{id:pe,duration:t,waveform:s}}}return a.startsWith("audio/")?{audio:{id:pe,mimeType:a,fileName:t,size:i,duration:200}}:{document:{mimeType:a,fileName:t,size:i,...s&&{previewBlobUrl:s}}}}function xe(e,t){return{poll:{id:String(t),summary:f(e.summary,["question","answers"]),results:{}}}}function Ve(e){const{className:t,offset:n,length:s}=e;return{type:t,offset:n,length:s,...e instanceof g.Api.MessageEntityMentionName&&{userId:N(e.userId,"user")},..."url"in e&&{url:e.url}}}function Ne(e,t,n){const{channelId:s,replies:a,maxId:i,readMaxId:o,recentRepliers:r}=e;if(!s)return;const c=N(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(F)}}:void 0}const Fe=e=>Math.floor(Date.now()/1e3)+e;function Le(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=Boolean("min"in e&&e.min),s="accessHash"in e&&String(e.accessHash),a="photo"in e&&e.photo&&Je(e.photo),i=Boolean("signatures"in e&&e.signatures),o=Boolean("hasLink"in e&&e.hasLink);return{isMin:n,hasPrivateLink:o,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},...Oe(e),..."creator"in e&&{isCreator:e.creator},...He(e),...Ge(e)}}function qe(e,t,n){const{peer:s,folderId:a,unreadMark:i,unreadCount:o,unreadMentionsCount:r,notifySettings:{silent:c,muteUntil:l},readOutboxMaxId:d,readInboxMaxId:u,draft:p}=e,f=c||"number"==typeof l&&Fe(n){let{platform:t}=e;return"all"===t}));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 Ge(e){return e instanceof g.Api.Chat&&e.migratedTo&&!(e.migratedTo instanceof g.Api.InputChannelEmpty)?{migratedTo:{chatId:F(e.migratedTo),...e.migratedTo instanceof g.Api.InputChannel&&{accessHash:String(e.migratedTo.accessHash)}}}:{}}function Ke(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];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:N(e.id,e instanceof g.Api.User?"user":"chat"),type:ze(e),title:e instanceof g.Api.User?$e(e):e.title,...Le(e,t)}}function ze(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 We(e){return x(e)?`user${e.userId}`:V(e)?`chat${e.chatId}`:`chat${e.channelId}`}function je(e,t){return x(e)?$e(t):t.title}function $e(e){return e.firstName?`${e.firstName}${e.lastName?` ${e.lastName}`:""}`:e.lastName||void 0}function Je(e){if("photoId"in e)return String(e.photoId)}function Qe(e){return{userId:e instanceof g.Api.ChannelParticipantBanned||e instanceof g.Api.ChannelParticipantLeft?F(e.peer):N(e.userId,"user"),inviterId:"inviterId"in e?N(e.inviterId,"user"):void 0,joinedDate:"date"in e?e.date:void 0,kickedByUserId:"kickedBy"in e?N(e.kickedBy,"user"):void 0,promotedByUserId:"promotedBy"in e?N(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 Xe(e){return e instanceof g.Api.ChatParticipants||e instanceof g.Api.channels.ChannelParticipants?e.participants.map(Qe).filter(Boolean):void 0}function Ze(e,t){let n,s="";if(!(e.action instanceof g.Api.SendMessageCancelAction)){if(e.action instanceof g.Api.SendMessageTypingAction)s="lng_user_typing";else if(e.action instanceof g.Api.SendMessageRecordVideoAction)s="lng_send_action_record_video";else if(e.action instanceof g.Api.SendMessageUploadVideoAction)s="lng_send_action_upload_video";else if(e.action instanceof g.Api.SendMessageRecordAudioAction)s="lng_send_action_record_audio";else if(e.action instanceof g.Api.SendMessageUploadAudioAction)s="lng_send_action_upload_audio";else if(e.action instanceof g.Api.SendMessageUploadPhotoAction)s="lng_send_action_upload_photo";else if(e.action instanceof g.Api.SendMessageUploadDocumentAction)s="lng_send_action_upload_file";else if(e.action instanceof g.Api.SendMessageGeoLocationAction)s="selecting a location to share";else if(e.action instanceof g.Api.SendMessageChooseContactAction)s="selecting a contact to share";else if(e.action instanceof g.Api.SendMessageGamePlayAction)s="lng_playing_game";else if(e.action instanceof g.Api.SendMessageRecordRoundAction)s="lng_send_action_record_round";else if(e.action instanceof g.Api.SendMessageUploadRoundAction)s="lng_send_action_upload_round";else if(e.action instanceof g.Api.SendMessageChooseStickerAction)s="lng_send_action_choose_sticker";else{if(e.action instanceof g.Api.SpeakingInGroupCallAction)return;if(e.action instanceof g.Api.SendMessageEmojiInteractionSeen)s="lng_user_action_watching_animations",n=e.action.emoticon;else if(e.action instanceof g.Api.SendMessageEmojiInteraction)return}return{action:s,...n&&{emoji:n},...!(e instanceof g.Api.UpdateUserTyping)&&{userId:F(e.fromId)},timestamp:Date.now()+1e3*t}}}function Ye(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(F).filter(Boolean),includedChatIds:e.includePeers.map(F).filter(Boolean),excludedChatIds:e.excludePeers.map(F).filter(Boolean)};var t,n}function et(e){let{filter:t,description:n}=e;return{...Ye(t),description:n}}function tt(e){return e.reduce(((e,t)=>{const n=N(t.userId,"user");return e.concat(t.commands.map((e=>({botId:n,..._(e)}))))}),[])}function nt(e){const{revoked:t,date:n,expireDate:s,link:a,permanent:i,startDate:o,usage:r,usageLimit:c,requested:l,requestNeeded:d,title:u,adminId:g}=e;return{isRevoked:t,date:n,expireDate:s,link:a,isPermanent:i,startDate:o,usage:r,usageLimit:c,isRequestNeeded:d,requested:l,title:u,adminId:N(g,"user")}}function st(e){let{autoarchived:t,reportSpam:n,addContact:s,blockContact:a}=e;return{isAutoArchived:Boolean(t),canReportSpam:Boolean(n),canAddContact:Boolean(s),canBlockContact:Boolean(a)}}function at(e){const{fullUser:{about:t,commonChatsCount:n,pinnedMsgId:s,botInfo:a,blocked:i},users:o}=e,r=it(o[0]);return{...r,fullInfo:{bio:t,commonChatsCount:n,pinnedMessageId:s,isBlocked:Boolean(i),...a&&{botDescription:a.description},...a&&a.commands.length&&{botCommands:rt(r.id,a)}}}}function it(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:N(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 ot(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 rt(e,t){return t.commands.map((t=>{let{command:n,description:s}=t;return{botId:e,command:n,description:s}}))}function ct(e){const t={},n=[];return e.forEach((e=>{const s=it(e);s&&(n.push(s),"status"in e&&(t[s.id]=ot(e.status)))})),{users:n,userStatusesById:t}}function lt(e){if(e instanceof g.Api.WallPaperNoFile)return;const{slug:t}=e,n=ke(e.document);return n?{slug:t,document:n}:void 0}function dt(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 ut(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=>N(e,"user"))):e instanceof g.Api.PrivacyValueDisallowUsers?a=e.users.map((e=>N(e,"user"))):e instanceof g.Api.PrivacyValueAllowChatParticipants?s=e.chats.map((e=>N(e,"chat"))):e instanceof g.Api.PrivacyValueDisallowChatParticipants&&(i=e.chats.map((e=>N(e,"chat"))))})),t||(t="nobody"),{visibility:t,allowUserIds:n||[],allowChatIds:s||[],blockUserIds:a||[],blockChatIds:i||[]}}function gt(e,t,n){const{silent:s,muteUntil:a,showPreviews:i,sound:o}=e;return{chatId:F(t),isMuted:s||"number"==typeof a&&Fe(n)(e[t.key]=ft(t.value),e)),{})}function ht(e){const{self:t,min:n,about:s,date:a,versioned:i,canSelfUnmute:o,justJoined:r,left:c,muted:l,mutedByYou:d,source:u,volume:g,volumeByAdmin:p,videoJoined:f,peer:h,video:m,presentation:_,raiseHandRating:y}=e;return{isSelf:t,isMin:n,canSelfUnmute:o,isLeft:c,isMuted:l,isMutedByMe:d,hasJustJoined:r,isVolumeByAdmin:p,isVersioned:i,isVideoJoined:f,about:s,source:u,raiseHandRating:null==y?void 0:y.toString(),volume:g,date:new Date(a),isUser:x(h),id:F(h),video:m?mt(m):void 0,presentation:_?mt(_):void 0}}function mt(e){const{audioSource:t,endpoint:n,paused:s,sourceGroups:a}=e;return{audioSource:t,endpoint:n,isPaused:s,sourceGroups:a.map(_t)}}function _t(e){return{semantics:e.semantics,sources:e.sources}}function yt(e){const{id:t,accessHash:n}=e;if(e instanceof g.Api.GroupCallDiscarded)return{connectionState:"discarded",id:t.toString(),accessHash:n.toString(),participantsCount:0,version:0,participants:{}};const{version:s,participantsCount:a,streamDcId:i,scheduleDate:o,canChangeJoinMuted:r,joinMuted:c,canStartVideo:l,scheduleStartSubscribed:d}=e;return{connectionState:"disconnected",isLoaded:!0,id:t.toString(),accessHash:n.toString(),version:s,participantsCount:a,streamDcId:i,scheduleDate:o,canChangeJoinMuted:r,joinMuted:c,canStartVideo:l,scheduleStartSubscribed:d,participants:{}}}let bt;const wt=new Set;let vt=0,It=!1;function Ct(e){e.filter((e=>e instanceof g.Api.User)).map(it).forEach((e=>{e&&bt({"@type":"updateUser",id:e.id,user:e})})),e.filter((e=>e instanceof g.Api.Chat||e instanceof g.Api.Channel)).map((e=>Ke(e))).forEach((e=>{e&&bt({"@type":"updateChat",id:e.id,chat:e})}))}function At(e,t){if(e instanceof g.connection.UpdateServerTimeOffset)vt=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"}bt({"@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=ye(N((i=e).chatId,"chat"),{...i,fromId:$(N(i.fromId,"user"))});else if(e instanceof g.Api.UpdateShortMessage)t=function(e){return ye(N(e.userId,"user"),{...e,fromId:$(e.out?fe:N(e.userId,"user"))})}(e);else{var n;if(e.message instanceof g.Api.MessageEmpty)return;e.message instanceof g.Api.Message&&ae(e.message)&&O(e.message),t=_e(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 a=e._entities;if(a&&(K(a),Ct(a)),e instanceof g.Api.UpdateNewScheduledMessage?bt({"@type":wt.has(t.id)?"updateScheduledMessage":"newScheduledMessage",id:t.id,chatId:t.chatId,message:t}):bt({"@type":wt.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.MessageActionPaymentSent)bt({"@type":"updatePaymentStateCompleted"});else if(n instanceof g.Api.MessageActionChatEditTitle)bt({"@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=Je(s),i=q(e.message);C.chats[i]&&(C.chats[i].photo=s),H(n.photo),a&&bt({"@type":"updateChat",id:t.chatId,chat:{avatarHash:a},...n.photo instanceof g.Api.Photo&&{newProfilePhoto:v(n.photo)}})}else if(n instanceof g.Api.MessageActionChatDeletePhoto){const n=q(e.message);C.chats[n]&&(C.chats[n].photo=new g.Api.ChatPhotoEmpty),bt({"@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&&Boolean(e.self)&&e.id===n.userId))&&(bt({"@type":"updateChat",id:t.chatId,chat:{isRestricted:!0}}),bt({"@type":"updateChatLeave",id:t.chatId})):n instanceof g.Api.MessageActionChatAddUser?e._entities&&e._entities.some((e=>e instanceof g.Api.User&&Boolean(e.self)&&n.users.includes(e.id)))&&bt({"@type":"updateChatJoin",id:t.chatId}):n instanceof g.Api.MessageActionGroupCall&&!n.duration&&n.call&&bt({"@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&&ae(e.message)&&O(e.message);const t=_e(e.message);bt({"@type":"updateMessage",id:t.id,chatId:t.chatId,message:t})}else if(e instanceof g.Api.UpdateMessageReactions)bt({"@type":"updateMessageReactions",id:e.msgId,chatId:F(e.peer),reactions:be(e.reactions)});else if(e instanceof g.Api.UpdateDeleteMessages)bt({"@type":"deleteMessages",ids:e.messages});else if(e instanceof g.Api.UpdateDeleteScheduledMessages)bt({"@type":"deleteScheduledMessages",ids:e.messages,chatId:F(e.peer)});else if(e instanceof g.Api.UpdateDeleteChannelMessages){const t=N(e.channelId,"channel"),n=e.messages,s=n.filter((e=>C.messages[`${t}-${e}`])),a=n.filter((e=>!C.messages[`${t}-${e}`])),i=n.map((e=>{const n=C.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&&bt({"@type":"deleteMessages",ids:s,chatId:t}),i.length&&bt({"@type":"deleteProfilePhotos",ids:i,chatId:t}),a.length&&setTimeout((()=>{bt({"@type":"deleteMessages",ids:a,chatId:t})}),1e3)}else if(e instanceof g.Api.UpdateServiceNotification)if(e.popup)bt({"@type":"error",error:{message:e.message}});else{const t=function(e,t){const n=he++,s=Ce(e);return{id:n,chatId:l,date:e.inboxDate||t,content:s,isOutgoing:!1}}(e,Date.now()/1e3+vt);ae(e)&&O(ne(t.id,t.chatId,e)),bt({"@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&&C.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:Ae(s.content.text.text,e.entities)}),e.media&&(a={...a,...Pe(e.media)});const t=ne(e.id,s.chatId,e);ae(t)&&O(t)}wt.add(e.id);const i="date"in e&&1e3*e.datee instanceof g.Api.DialogPeer)).map((e=>F(e.peer))):[];bt({"@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;bt({"@type":"updateChatListType",id:F(n),folderId:t})}));else if(e instanceof g.Api.UpdateDialogFilter){const{id:t,filter:n}=e,s=n?Ye(n):void 0;bt({"@type":"updateChatFolder",id:t,folder:s})}else if(e instanceof g.Api.UpdateDialogFilterOrder)bt({"@type":"updateChatFoldersOrder",orderedIds:e.order});else if(e instanceof g.Api.UpdateChatParticipants){const t=Xe(e.participants);bt({"@type":"updateChatMembers",id:N(e.participants.chatId,"chat"),replacedMembers:t})}else if(e instanceof g.Api.UpdateChatParticipantAdd){const t=Qe(f(e,["userId","inviterId","date"]));bt({"@type":"updateChatMembers",id:N(e.chatId,"chat"),addedMember:t})}else if(e instanceof g.Api.UpdateChatParticipantDelete)bt({"@type":"updateChatMembers",id:N(e.chatId,"chat"),deletedMemberId:N(e.userId,"user")});else if(e instanceof g.Api.UpdatePinnedMessages||e instanceof g.Api.UpdatePinnedChannelMessages){const t=e instanceof g.Api.UpdatePinnedMessages?F(e.peer):N(e.channelId,"channel");bt({"@type":"updatePinnedIds",chatId:t,messageIds:e.messages,isPinned:e.pinned})}else if(e instanceof g.Api.UpdateNotifySettings&&e.peer instanceof g.Api.NotifyPeer)bt({"@type":"updateNotifyExceptions",...gt(e.notifySettings,e.peer.peer,vt)});else if(e instanceof g.Api.UpdateUserTyping||e instanceof g.Api.UpdateChatUserTyping){const t=e instanceof g.Api.UpdateUserTyping?N(e.userId,"user"):N(e.chatId,"chat");e.action instanceof g.Api.SendMessageEmojiInteraction?bt({"@type":"updateStartEmojiInteraction",id:t,emoji:e.action.emoticon,messageId:e.action.msgId,interaction:(a=JSON.parse(e.action.interaction.data),{timestamps:a.a.map((e=>e.t))})}):bt({"@type":"updateChatTypingStatus",id:t,typingStatus:Ze(e,vt)})}else if(e instanceof g.Api.UpdateChannelUserTyping){const t=N(e.channelId,"channel");bt({"@type":"updateChatTypingStatus",id:t,typingStatus:Ze(e,vt)})}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(It)return void(It=!1);t instanceof g.Api.messages.ToggleNoForwards&&(It=!0,setTimeout((()=>{It=!1}),2e3));const n=Ke(s);n&&(bt({"@type":"updateChat",id:n.id,chat:n}),bt({"@type":n.isNotJoined?"updateChatLeave":"updateChatJoin",id:N(e.channelId,"channel")}))}else if(s instanceof g.Api.ChannelForbidden){const t=N(e.channelId,"channel");bt({"@type":"updateChat",id:t,chat:{isRestricted:!0}}),bt({"@type":"updateChatLeave",id:t})}else 0===n.length&&bt({"@type":"resetMessages",id:N(e.channelId,"channel")})}else if(e instanceof g.Api.UpdateDialogUnreadMark&&e.peer instanceof g.Api.DialogPeer)bt({"@type":"updateChat",id:F(e.peer.peer),chat:{hasUnreadMark:e.unread}});else if(e instanceof g.Api.UpdateChatDefaultBannedRights)bt({"@type":"updateChat",id:F(e.peer),chat:{defaultBannedRights:_(e.defaultBannedRights)}});else if(e instanceof g.Api.UpdateUserStatus)bt({"@type":"updateUserStatus",userId:N(e.userId,"user"),status:ot(e.status)});else if(e instanceof g.Api.UpdateUserName){const t=N(e.userId,"user"),n=C.users[t],s=null!=n&&n.mutualContact&&!n.self?f(e,["username"]):f(e,["firstName","lastName","username"]);bt({"@type":"updateUser",id:t,user:s})}else if(e instanceof g.Api.UpdateUserPhoto){const{userId:t,photo:n}=e,s=N(t,"user"),a=Je(n);C.users[s]&&(C.users[s].photo=n),bt({"@type":"updateUser",id:s,user:{avatarHash:a}})}else if(e instanceof g.Api.UpdateUserPhone){const{userId:t,phone:n}=e;bt({"@type":"updateUser",id:N(t,"user"),user:{phoneNumber:n}})}else if(e instanceof g.Api.UpdatePeerSettings){const{_entities:t,settings:n}=e;if(!t)return;null!=t&&t.length&&(t.filter((e=>e instanceof g.Api.User&&!e.contact)).forEach((e=>{bt({"@type":"deleteContact",id:N(e.id,"user")})})),t.filter((e=>e instanceof g.Api.User&&e.contact)).map(it).forEach((e=>{e&&bt({"@type":"updateUser",id:e.id,user:{...e,...n&&{settings:st(n)}}})})))}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;bt({"@type":"updateNotifySettings",peerType:i,isSilent:Boolean(n||"number"==typeof s&&Date.now()+1e3*vt<1e3*s),shouldShowPreviews:Boolean(t)})}else if(e instanceof g.Api.UpdatePeerBlocked)bt({"@type":"updatePeerBlocked",id:F(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&&bt({"@type":"updatePrivacy",key:t,rules:ut(e.rules)})}else if(e instanceof g.Api.UpdateDraftMessage)bt({"@type":"draftMessage",chatId:F(e.peer),...Se(e.draft)});else if(e instanceof g.Api.UpdateContactsReset)bt({"@type":"updateResetContactList"});else if(e instanceof g.Api.UpdateFavedStickers)bt({"@type":"updateFavoriteStickers"});else if(e instanceof g.Api.UpdateGroupCall)bt({"@type":"updateGroupCall",call:yt(e.call)});else if(e instanceof g.Api.UpdateGroupCallConnection)bt({"@type":"updateGroupCallConnection",data:JSON.parse(e.params.data),presentation:Boolean(e.presentation)});else if(e instanceof g.Api.UpdateGroupCallParticipants){const t=e._entities;t&&(K(t),Ct(t)),bt({"@type":"updateGroupCallParticipants",groupCallId:(s=e.call,s.id.toString()),participants:e.participants.map(ht)})}else if(e instanceof g.Api.UpdatePendingJoinRequests){const t=e._entities;t&&(K(t),Ct(t)),bt({"@type":"updatePendingJoinRequests",chatId:F(e.peer),recentRequesterIds:e.recentRequesters.map((e=>N(e,"user"))),requestsPending:e.requestsPending})}var s,a,i}const St={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."},Pt={};let Mt;function kt(){return Mt(Tt("authorizationStateWaitPhoneNumber")),new Promise(((e,t)=>{Pt.resolve=e,Pt.reject=t}))}function Rt(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return Mt({...Tt("authorizationStateWaitCode"),isCodeViaApp:e}),new Promise(((e,t)=>{Pt.resolve=e,Pt.reject=t}))}function Ut(e){return Mt({...Tt("authorizationStateWaitPassword"),hint:e}),new Promise((e=>{Pt.resolve=e}))}function Et(){return Mt(Tt("authorizationStateWaitRegistration")),new Promise((e=>{Pt.resolve=e}))}function Dt(e){return Mt({...Tt("authorizationStateWaitQrCode"),qrCode:{token:btoa(String.fromCharCode(...e.token)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),expires:e.expires}}),new Promise(((e,t)=>{Pt.reject=t}))}function Bt(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=St[e.message];t||(t="Unexpected Error"),Mt({"@type":"updateAuthorizationError",message:t})}function Tt(e){return{"@type":"updateAuthorizationState",authorizationState:e}}function xt(e){Pt.resolve&&Pt.resolve(e)}function Vt(e){Pt.resolve&&Pt.resolve(e)}function Nt(e){Pt.resolve&&Pt.resolve(e)}function Ft(e){const{firstName:t,lastName:n}=e;Pt.resolve&&Pt.resolve([t,n])}function Lt(){Pt.reject&&Pt.reject(new Error("RESTART_AUTH"))}function qt(){Pt.reject&&Pt.reject(new Error("RESTART_AUTH_WITH_QR"))}var Ot=n(9832);const Ht=self.caches;let Gt;async function Kt(e,t,n){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(Ht)try{const a=new Request(t.replace(/:/g,"_")),i=await Ht.open(e),o=await i.match(a);if(!o)return;const r=o.headers.get("Content-Type");switch(n){case Gt.Text:return await o.text();case Gt.Blob:{if(t.startsWith("avatar")&&r&&r.startsWith("text"))return;const e=await o.blob(),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 Gt.Json:return await o.json();default:return}}catch(e){return void console.warn(e)}}async function zt(e,t,n){if(Ht)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 Ht.open(e);return await o.put(a,i)}catch(e){return void console.warn(e)}}async function Wt(e){try{if(!Ht)return;return await Ht.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"}(Gt||(Gt={}));const jt=new Set(["msg","sticker","gif","wallpaper","photo","webDocument","document"]);function $t(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"image/jpeg";if(e.length<4)return t;let n=t;const s=e.subarray(0,4).reduce(((e,t)=>e+t.toString(16)),"");switch(s){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}Ot.Logger.setLevel("warn");const Jt={build:e=>e};let Qt,Xt,Zt=!1;async function Yt(){await sn(new g.Api.auth.LogOut),await Xt.destroy()}async function en(){await Xt.disconnect()}function tn(e){Qt({"@type":"updateSession",sessionData:e})}function nn(e){e instanceof g.connection.UpdateConnectionState?Zt=e.state===g.connection.UpdateConnectionState.connected:e instanceof g.Api.UpdatesTooLong?async function(){try{await sn(new g.Api.users.GetFullUser({id:new g.Api.InputUserSelf}),void 0,!0)}catch(e){"AUTH_KEY_UNREGISTERED"===e.message&&Qt({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}}():e instanceof g.connection.UpdateServerTimeOffset&&Qt({"@type":"updateServerTimeOffset",serverTimeOffset:e.timeOffset})}async function sn(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=arguments.length>3&&void 0!==arguments[3]&&arguments[3],a=arguments.length>4?arguments[4]:void 0;if(Zt)try{const n=await Xt.invoke(e,a);return s||an(e,n),t?n&&!0:n}catch(t){if(n)throw t;return void dn(t,e)}}function an(e,t){let n,s;t instanceof g.Api.UpdatesCombined||t instanceof g.Api.Updates?n=t:"object"==typeof t&&"updates"in t&&(t.updates instanceof g.Api.Updates||t.updates instanceof g.Api.UpdatesCombined)?n=t.updates:(t instanceof g.Api.UpdateShortMessage||t instanceof g.Api.UpdateShortChatMessage||t instanceof g.Api.UpdateShort||t instanceof g.Api.UpdateShortSentMessage)&&(s=t),n?(function(e){const t=[...e.users,...e.chats];e.updates.forEach((e=>{t&&(e._entities=t)}))}(n),n.updates.forEach((t=>{At(t,e)}))):s&&At(s,e)}function on(e,t){return async function(e,t,n,a){let{url:i,mediaFormat:o,start:r,end:c,isHtmlAllowed:l}=e;const{data:d,mimeType:u,fullSize:p}=await async function(e,t,n,s,a,i,o,r){const c=e.startsWith("staticMap")?e.match(/(staticMap):([0-9-]+)(\?.+)/):e.startsWith("webDocument")?e.match(/(webDocument):(.+)/):e.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file|document)([-\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 l;const d=c[2],u=c[3]?c[3].replace("?size=",""):void 0;let p;if("staticMap"===c[1]){const e=c[2],n=c[3],s=new URLSearchParams(n),a=s.get("long"),i=s.get("lat"),o=s.get("w"),r=s.get("h"),l=s.get("zoom"),d=s.get("scale"),u=s.get("accuracy_radius");return{mimeType:"image/png",data:await t.downloadStaticMap(e,a,i,o,r,l,d,u)}}switch(l="avatar"===c[1]||"profile"===c[1]?j(d):c[1],l){case"channel":case"chat":p=C.chats[d];break;case"user":p=C.users[d];break;case"msg":p=C.messages[d];break;case"sticker":case"gif":case"wallpaper":case"document":p=C.documents[d];break;case"photo":p=C.photos[d];break;case"stickerSet":p=C.stickerSets[d];break;case"webDocument":p=C.webDocuments[d]}if(p){if(jt.has(l)){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.MessageMediaGeo||e.media instanceof g.Api.MessageMediaVenue||e.media instanceof g.Api.MessageMediaGeoLive?"image/png":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?t?"image/jpeg":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"===l&&u?n="image/webp":"webDocument"===l?n=p.mimeType:(n=p.mimeType,c=p.size),!r&&n&&(n=n.replace(/html/gi,"")),{mimeType:n,data:e,fullSize:c}}if("stickerSet"===l){const e=await t.downloadStickerSetThumb(p);return{mimeType:o===T.Lottie?"application/x-tgsticker":$t(e),data:e}}{const e=await t.downloadProfilePhoto(p,"profile"===c[1]);return{mimeType:$t(e),data:e}}}}(i,t,n,a,r,c,o,l)||{};if(!d)return;const f=await async function(e,t,n){switch(t){case T.BlobUrl:case T.Lottie:return new Blob([e],{type:n});case T.Progressive:return e.buffer}}(d,o,u);if(!f)return;const h=o!==T.Progressive&&(o!==T.BlobUrl||f.size<=524288);return s&&h&&zt(i.startsWith("avatar")?"tt-media-avatars":"tt-media",i,f),{prepared:o===T.Progressive?"":(m=f,m instanceof Blob?URL.createObjectURL(m):m),arrayBuffer:o===T.Progressive?f:void 0,mimeType:u,fullSize:p};var m}(e,Xt,Zt,t)}function rn(e,t){return Xt.uploadFile({file:e,onProgress:t,workers:16})}function cn(e){return Xt.updateTwoFaSettings(e)}async function ln(){const e=await sn(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];C.users[N(t.id,"user")]=t;const n=at(e);var s;s=n.id,fe=s,function(e){Mt({"@type":"updateCurrentUser",currentUser:e})}(n)}function dn(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;Qt({"@type":"error",error:{message:s,isSlowMode:n,hasErrorKey:!0}})}const un=2**31-1;let gn;async function pn(e){let{limit:t,offsetDate:n,archived:s,withPinned:a,serverTimeOffset:i,lastLocalServiceMessage:o}=e;const r=await sn(new g.Api.messages.GetDialogs({offsetPeer:new g.Api.InputPeerEmpty,limit:t,offsetDate:n,folderId:s?1:void 0,...a&&{excludePinned:!0}})),c=a?await sn(new g.Api.messages.GetPinnedDialogs({folderId:s?1:void 0})):void 0;if(!r||r instanceof g.Api.messages.DialogsNotModified)return;c&&ts(c),ts(r);const d=p((c?c.messages:[]).concat(r.messages).map(_e).filter(Boolean),"chatId"),u={...c&&es(c),...es(r)},f=[],h={},m={},_=(c?c.dialogs:[]).concat(r.dialogs),y=[];_.forEach((e=>{if(!(e instanceof g.Api.Dialog)||!s&&1===e.folderId||s&&1!==e.folderId)return;const t=qe(e,u[We(e.peer)],i);if(t.id===l&&o&&(!d[t.id]||o.date>d[t.id].date)?t.lastMessage=o:t.lastMessage=d[t.id],t.isListed=!0,f.push(t),a&&e.pinned&&y.push(t.id),e.draft){const{formattedText:n,replyingToId:s}=Se(e.draft)||{};n&&(h[t.id]=n),s&&(m[t.id]=s)}}));const b=f.map((e=>e.id)),{users:w,userStatusesById:v}=ct(((null==c?void 0:c.users)||[]).concat(r.users));let I;return I=r instanceof g.Api.messages.DialogsSlice?r.count:b.length,{chatIds:b,chats:f,users:w,userStatusesById:v,draftsById:h,replyingToById:m,orderedPinnedIds:a?y:void 0,totalChatCount:I}}function fn(e){const{id:t,accessHash:n,adminRights:s}=e;return X(t,n)instanceof g.Api.InputChannel?async function(e,t,n){var s;const a=await sn(new g.Api.channels.GetFullChannel({channel:X(e,t)}));if(!(a&&a.fullChat instanceof g.Api.ChannelFull))return;const{about:i,onlineCount:o,exportedInvite:r,slowmodeSeconds:c,slowmodeNextSendDate:l,migratedFromChatId:d,migratedFromMaxId:u,canViewParticipants:p,canViewStats:f,linkedChatId:h,hiddenPrehistory:m,call:_,botInfo:y,availableReactions:b,defaultSendAs:w,requestsPending:v,recentRequesters:I,statsDc:C,participantsCount:A}=a.fullChat,S=r instanceof g.Api.ChatInviteExported?r.link:void 0,{members:P,users:M}=p&&await jn(e,t)||{},{members:k,users:R}=p&&n&&await jn(e,t,"kicked")||{},{members:U,users:E}=p&&n&&await jn(e,t,"admin")||{},D=y?tt(y):void 0;if((null==a||null===(s=a.chats)||void 0===s?void 0:s.length)>1){ts(a);const[,e]=a.chats,t=Ke(e,void 0,!0);t&&gn({"@type":"updateChat",id:t.id,chat:t})}return{fullInfo:{about:i,onlineCount:o,inviteLink:S,slowMode:c?{seconds:c,nextSendDate:l}:void 0,migratedFrom:d?{chatId:N(d,"chat"),maxMessageId:u}:void 0,canViewMembers:p,canViewStatistics:f,isPreHistoryHidden:m,members:P,kickedMembers:k,adminMembers:U,groupCallId:_?String(_.id):void 0,linkedChatId:h?N(h,"chat"):void 0,botCommands:D,enabledReactions:b,sendAsId:w?F(w):void 0,requestsPending:v,recentRequesterIds:null==I?void 0:I.map((e=>N(e,"user"))),statisticsDcId:C},users:[...M||[],...R||[],...E||[]],groupCall:_?{chatId:e,isLoaded:!1,id:_.id.toString(),accessHash:null==_?void 0:_.accessHash.toString(),participants:{},version:0,participantsCount:0,connectionState:"disconnected"}:void 0,membersCount:A}}(t,n,s):async function(e){const t=await sn(new g.Api.messages.GetFullChat({chatId:X(e)}));if(!(t&&t.fullChat instanceof g.Api.ChatFull))return;ts(t);const{about:n,participants:s,exportedInvite:a,botInfo:i,call:o,availableReactions:r,recentRequesters:c,requestsPending:l}=t.fullChat,d=Xe(s),u=d?d.filter((e=>{let{isAdmin:t,isOwner:n}=e;return t||n})):void 0;return{fullInfo:{about:n,members:d,adminMembers:u,canViewMembers:!0,botCommands:i?tt(i):void 0,...a&&{inviteLink:a.link},groupCallId:null==o?void 0:o.id.toString(),enabledReactions:r,requestsPending:l,recentRequesterIds:null==c?void 0:c.map((e=>N(e,"user")))},users:t.users.map(it).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,membersCount:null==d?void 0:d.length}}(t)}async function hn(e){const{id:t,accessHash:n}=e,s=await sn(new g.Api.messages.GetPeerSettings({peer:J(t,n)}));if(s)return st(s.settings)}async function mn(e){let{query:t}=e;const n=await sn(new g.Api.contacts.Search({q:t}));if(!n)return;ts(n);const s=n.myResults.map(F),a=n.chats.concat(n.users).map((e=>Ke(e))).filter(Boolean),i=n.users.map(it).filter((e=>Boolean(e)&&!e.isSelf));return{localChats:a.filter((e=>s.includes(e.id))),localUsers:i.filter((e=>s.includes(e.id))),globalChats:a.filter((e=>!s.includes(e.id))),globalUsers:i.filter((e=>!s.includes(e.id)))}}async function _n(e){let t,{type:n,user:s}=e;if("self"===n||"user"===n){const e=await sn(new g.Api.users.GetUsers({id:["user"===n&&s?X(s.id,s.accessHash):new g.Api.InputUserSelf]}));if(!e||!e.length)return;[t]=e}else if("support"===n){const e=await sn(new g.Api.help.GetSupport);if(!e||!e.user)return;t=e.user}const a=Ke(t,"support"===n);if(a)return gn({"@type":"updateChat",id:a.id,chat:a}),{chatId:a.id}}async function yn(e){let{chat:t,serverTimeOffset:n,lastLocalMessage:s,noLastMessage:a}=e;const{id:i,accessHash:o}=t,r=await sn(new g.Api.messages.GetPeerDialogs({peers:[new g.Api.InputDialogPeer({peer:J(i,o)})]}));if(!r)return;const c=r.dialogs[0];if(!(c&&c instanceof g.Api.Dialog))return;const l=es(r)[We(c.peer)];if(!l)return;ts(r);const d=_e(r.messages[0]),u=s&&(!d||s.date>d.date)?s:d;gn({"@type":"updateChat",id:i,chat:{...qe(c,l,n),...!a&&{lastMessage:u}}})}function bn(e){let{chat:t,text:n,entities:s,replyToMsgId:a}=e;return sn(new g.Api.messages.SaveDraft({peer:J(t.id,t.accessHash),message:n,...s&&{entities:s.map(se)},replyToMsgId:a}))}function wn(e){return sn(new g.Api.messages.SaveDraft({peer:J(e.id,e.accessHash),message:""}))}async function vn(e){let{chat:t,isMuted:n,serverTimeOffset:s}=e;await sn(new g.Api.account.UpdateNotifySettings({peer:new g.Api.InputNotifyPeer({peer:J(t.id,t.accessHash)}),settings:new g.Api.InputPeerNotifySettings({muteUntil:n?un:0})})),gn({"@type":"updateNotifyExceptions",chatId:t.id,isMuted:n}),yn({chat:t,serverTimeOffset:s,noLastMessage:!0})}async function In(e){let{title:t,about:n="",users:s}=e,a=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=await sn(new g.Api.channels.CreateChannel({broadcast:!0,title:t,about:n}));if(!(i instanceof g.Api.Updates))return;const o=i.chats[0];if(!(o&&o instanceof g.Api.Channel))return;const r=Ke(o);if(null!=s&&s.length)try{await sn(new g.Api.channels.InviteToChannel({channel:X(r.id,r.accessHash),users:s.map((e=>{let{id:t,accessHash:n}=e;return X(t,n)}))}),void 0,a)}catch(e){}return r}function Cn(e){let{channelId:t,accessHash:n}=e;return sn(new g.Api.channels.JoinChannel({channel:X(t,n)}),!0)}function An(e){let{chat:t,user:n}=e;if("chatTypeBasicGroup"===t.type)return sn(new g.Api.messages.DeleteChatUser({chatId:X(t.id,t.accessHash),userId:X(n.id,n.accessHash)}),!0)}function Sn(e){let{chatId:t}=e;return sn(new g.Api.messages.DeleteChat({chatId:X(t)}),!0)}function Pn(e){let{channelId:t,accessHash:n}=e;return sn(new g.Api.channels.LeaveChannel({channel:X(t,n)}),!0)}function Mn(e){let{channelId:t,accessHash:n}=e;return sn(new g.Api.channels.DeleteChannel({channel:X(t,n)}),!0)}async function kn(e){let{title:t,users:n}=e;const s=await sn(new g.Api.messages.CreateChat({title:t,users:n.map((e=>{let{id:t,accessHash:n}=e;return X(t,n)}))}),void 0,!0);if(!(s instanceof g.Api.Updates))return;const a=s.chats[0];return a&&a instanceof g.Api.Chat?Ke(a):void 0}async function Rn(e){let{chatId:t,accessHash:n,photo:s}=e;const a=await rn(s),i=X(t,n);return sn(i instanceof g.Api.InputChannel?new g.Api.channels.EditPhoto({channel:i,photo:new g.Api.InputChatUploadedPhoto({file:a})}):new g.Api.messages.EditChatPhoto({chatId:i,photo:new g.Api.InputChatUploadedPhoto({file:a})}),!0)}async function Un(e){let{chat:t,shouldBePinned:n}=e;const{id:s,accessHash:a}=t;await sn(new g.Api.messages.ToggleDialogPin({peer:new g.Api.InputDialogPeer({peer:J(s,a)}),pinned:n||void 0}))&&gn({"@type":"updateChatPinned",id:t.id,isPinned:n})}function En(e){let{chat:t,folderId:n}=e;const{id:s,accessHash:a}=t;return sn(new g.Api.folders.EditPeerFolders({folderPeers:[new g.Api.InputFolderPeer({peer:J(s,a),folderId:n})]}),!0)}async function Dn(){const e=await sn(new g.Api.messages.GetDialogFilters);if(e)return{byId:p(e.map(Ye),"id"),orderedIds:e.map((e=>{let{id:t}=e;return t}))}}async function Bn(){const e=await sn(new g.Api.messages.GetSuggestedDialogFilters);if(e)return e.map(et)}async function Tn(e){let{id:t,folderUpdate:n}=e;const s=function(e){const{emoticon:t,contacts:n,nonContacts:s,groups:a,channels:i,bots:o,excludeArchived:r,excludeMuted:c,excludeRead:l,pinnedChatIds:d,includedChatIds:u,excludedChatIds:p}=e,f=d?d.map(Q).filter(Boolean):[],h=u?u.map(Q).filter(Boolean):[],m=p?p.map(Q).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:l||void 0,broadcasts:i||void 0,pinnedPeers:f,includePeers:h,excludePeers:m})}(n);await sn(new g.Api.messages.UpdateDialogFilter({id:t,filter:s}))&&gn({"@type":"updateChatFolder",id:t,folder:n})}async function xn(e){const t=await sn(new g.Api.messages.UpdateDialogFilter({id:e,filter:void 0})),n=await Bn();t&&gn({"@type":"updateChatFolder",id:e,folder:void 0}),n&&gn({"@type":"updateRecommendedChatFolders",folders:n})}async function Vn(e){let{chat:t,hasUnreadMark:n}=e;const{id:s,accessHash:a}=t;await sn(new g.Api.messages.MarkDialogUnread({peer:new g.Api.InputDialogPeer({peer:J(s,a)}),unread:n||void 0}))&&gn({"@type":"updateChat",id:t.id,chat:{hasUnreadMark:n}})}async function Nn(e){return Ln(await sn(new g.Api.contacts.ResolvePhone({phone:e})))}async function Fn(e){return Ln(await sn(new g.Api.contacts.ResolveUsername({username:e})))}function Ln(e){if(!e)return;const{users:t,chats:n}=e,s=n.length?Ke(n[0]):Ke(t[0]);return s?(ts(e),s):void 0}function qn(e){let{chat:t,isEnabled:n}=e;const{id:s,accessHash:a}=t,i=X(s,a);return sn(new g.Api.channels.TogglePreHistoryHidden({channel:i,enabled:n}),!0)}function On(e){let{chat:t,bannedRights:n}=e;const{id:s,accessHash:a}=t,i=J(s,a);return sn(new g.Api.messages.EditChatDefaultBannedRights({peer:i,bannedRights:oe(n)}),!0)}function Hn(e){let{chat:t,user:n,bannedRights:s,untilDate:a}=e;const i=X(t.id,t.accessHash),o=J(n.id,n.accessHash);return sn(new g.Api.channels.EditBanned({channel:i,participant:o,bannedRights:oe(s,a)}),!0)}function Gn(e){let{chat:t,user:n,adminRights:s,customTitle:a=""}=e;const i=X(t.id,t.accessHash),o=X(n.id,n.accessHash);return sn(new g.Api.channels.EditAdmin({channel:i,userId:o,adminRights:re(s),rank:a}),!0)}async function Kn(e,t){const n=X(e.id,e.accessHash);await sn(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 zn(e,t){await sn(new g.Api.messages.EditChatAbout({peer:J(e.id,e.accessHash),about:t}))&&gn({"@type":"updateChatFullInfo",id:e.id,fullInfo:{about:t}})}function Wn(e){let{chat:t,isEnabled:n}=e;const{id:s,accessHash:a}=t,i=X(s,a);return sn(new g.Api.channels.ToggleSignatures({channel:i,enabled:n}),!0)}async function jn(e,t){let n,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"recent",a=arguments.length>3?arguments[3]:void 0;switch(s){case"kicked":n=new g.Api.ChannelParticipantsKicked({q:""});break;case"admin":n=new g.Api.ChannelParticipantsAdmins;break;default:n=new g.Api.ChannelParticipantsRecent}const i=await sn(new g.Api.channels.GetParticipants({channel:X(e,t),filter:n,offset:a,limit:200}));if(i&&!(i instanceof g.Api.channels.ChannelParticipantsNotModified))return ts(i),{members:Xe(i),users:i.users.map(it).filter(Boolean)}}async function $n(){const e=await sn(new g.Api.channels.GetGroupsForDiscussion);if(e)return ts(e),e.chats.map((e=>Ke(e)))}function Jn(e){let{channel:t,chat:n}=e;return sn(new g.Api.channels.SetDiscussionGroup({broadcast:J(t.id,t.accessHash),group:n?J(n.id,n.accessHash):new g.Api.InputChannelEmpty}),!0)}async function Qn(e){const t=await sn(new g.Api.messages.MigrateChat({chatId:X(e.id)}));if(t&&t instanceof g.Api.Updates)return ts(t),Ke(t.chats[1])}async function Xn(e){const t=await sn(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,megagroup:c}=t;n instanceof g.Api.Photo&&H(t.photo),gn({"@type":"showInvite",data:{title:a,about:r,hash:e,participantsCount:s,isChannel:i&&!c,isRequestNeeded:o,...n instanceof g.Api.Photo&&{photo:v(n)}}})}else n=Ke(t.chat),n&&gn({"@type":"updateChat",id:n.id,chat:n});return n?{chatId:n.id}:void 0}async function Zn(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];try{return"chatTypeChannel"===e.type||"chatTypeSuperGroup"===e.type?await sn(new g.Api.channels.InviteToChannel({channel:X(e.id,e.accessHash),users:t.map((e=>X(e.id,e.accessHash)))}),!0,n):await Promise.all(t.map((t=>sn(new g.Api.messages.AddChatUser({chatId:X(e.id),userId:X(t.id,t.accessHash)}),!0,n))))}catch(e){return}}function Yn(e,t){return"chatTypeChannel"===e.type||"chatTypeSuperGroup"===e.type?Hn({chat:e,user:t,bannedRights:{viewMessages:!0,sendMessages:!0,sendMedia:!0,sendStickers:!0,sendGifs:!0,sendGames:!0,sendInline:!0,embedLinks:!0,sendPolls:!0,changeInfo:!0,inviteUsers:!0,pinMessages:!0},untilDate:un}):sn(new g.Api.messages.DeleteChatUser({chatId:X(e.id),userId:X(t.id,t.accessHash)}),!0)}function es(e){const t={};return e.chats.forEach((e=>{t[`chat${e.id}`]=e})),e.users.forEach((e=>{t[`user${e.id}`]=e})),t}function ts(e){"users"in e&&K(e.users),"chats"in e&&K(e.chats),"messages"in e&&e.messages.forEach((e=>{e instanceof g.Api.Message&&ae(e)&&O(e)}))}async function ns(e){let{hash:t}=e;const n=await sn(new g.Api.messages.ImportChatInvite({hash:t}));if(n instanceof g.Api.Updates&&n.chats.length)return Ke(n.chats[0])}function ss(e){let{chat:t,enabledReactions:n}=e;return sn(new g.Api.messages.SetChatAvailableReactions({peer:J(t.id,t.accessHash),availableReactions:n}),!0)}function as(e){let{chat:t,isProtected:n}=e;const{id:s,accessHash:a}=t;return sn(new g.Api.messages.ToggleNoForwards({peer:J(s,a),enabled:n}),!0)}function is(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}),is(this,"name",void 0),Object.assign(this,s)}else super(e),is(this,"name",void 0);this.name=t}});var os=n(8764).Buffer;let rs;async function cs(e){let{chat:t,threadId:n,...s}=e;const a=-1===n?g.Api.messages.GetHistory:g.Api.messages.GetReplies;let i;try{i=await sn(new a({peer:J(t.id,t.accessHash),...-1!==n&&{msgId:n},...s}),void 0,!0)}catch(e){"CHANNEL_PRIVATE"===e.message&&rs({"@type":"updateChat",id:t.id,chat:{isRestricted:!0}})}if(!i||i instanceof g.Api.messages.MessagesNotModified||!i.messages)return;xs(i);const o=i.messages.map(_e).filter(Boolean),r=i.users.map(it).filter(Boolean),c=i.chats.map((e=>Ke(e))).filter(Boolean),l=o.map((e=>{let{threadInfo:t}=e;return t})).filter(Boolean);return{messages:o,users:r,chats:c,threadInfos:l}}async function ls(e){let{chat:t,messageId:n}=e;const s="channel"===j(t.id);let a;try{a=await sn(s?new g.Api.channels.GetMessages({channel:X(t.id,t.accessHash),id:[new g.Api.InputMessageID({id:n})]}):new g.Api.messages.GetMessages({id:[new g.Api.InputMessageID({id:n})]}),void 0,!0)}catch(e){const{message:t}=e;"CHANNEL_PRIVATE"!==t&&rs({"@type":"error",error:{message:t,isSlowMode:!1,hasErrorKey:!0}})}if(!a||a instanceof g.Api.messages.MessagesNotModified)return;const i=a.messages[0];if(!i)return;if(i instanceof g.Api.MessageEmpty)return"MESSAGE_DELETED";const o=i&&_e(i);return o?(i instanceof g.Api.Message&&O(i),{message:o,users:a.users.map(it).filter(Boolean)}):void 0}let ds=Promise.resolve();function us(e,t){let{chat:n,text:s,entities:a,replyingTo:i,attachment:o,sticker:r,gif:c,poll:l,contact:d,isSilent:u,scheduledAt:p,groupedId:f,noWebPage:h,sendAs:m,serverTimeOffset:_}=e;const y=function(e,t,n,s,a,i,o,r,c,l,d,u){let g=arguments.length>12&&void 0!==arguments[12]?arguments[12]:0;const p=he++,f=a&&Te(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&&xe(r,p),...c&&{contact:c}},date:d||Math.round(Date.now()/1e3)+g,isOutgoing:!h,senderId:(null==u?void 0:u.id)||fe,...s&&{replyToMessageId:s},...l&&{groupedId:l,...f&&(f.photo||f.video)&&{isInAlbum:!0}},...d&&{isScheduled:!0}}}(n,s,a,i,o,r,c,l,d,f,p,m,_);rs({"@type":y.isScheduled?"newScheduledMessage":"newMessage",id:y.id,chatId:n.id,message:y}),setTimeout((()=>{rs({"@type":y.isScheduled?"updateScheduledMessage":"updateMessage",id:y.id,chatId:n.id,message:{sendingState:"messageSendingStatePending"}})}),1e3);const b=te();if(C.localMessages[String(b)]=y,f)return function(e,t,n,s){let{chat:a,text:i,entities:o,replyingTo:r,attachment:c,groupedId:l,isSilent:d,scheduledAt:u,sendAs:p}=e,f=-1;gs[l]||(gs[l]={counter:0,singleMediaByIndex:{}}),f=gs[l].counter++;const h=ds;return ds=(async()=>{let e;try{e=await hs(n,c,s)}catch(e){return gs[l].counter--,void await h}const m=await async function(e,t){const n=await sn(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})})}}(J(a.id,a.accessHash),e);if(await h,!m)return void gs[l].counter--;if(gs[l].singleMediaByIndex[f]=new g.Api.InputSingleMedia({media:m,randomId:t,message:i||"",entities:o?o.map(se):void 0}),Object.keys(gs[l].singleMediaByIndex).length{let e;if(o)try{e=await hs(y,o,t)}catch(e){return void await w}else r?e=ee(r):c?e=ee(c):l?e=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((e=>{let{text:t,option:n}=e;return new g.Api.PollAnswer({text:t,option:W(n)})})),quiz:n.quiz,multipleChoice:n.multipleChoice});if(!s)return new g.Api.InputMediaPoll({poll:a});const i=s.correctAnswers.map(W),{solution:o}=s,r=s.solutionEntities?s.solutionEntities.map(se):[];return new g.Api.InputMediaPoll({poll:a,correctAnswers:i,...o&&{solution:o,solutionEntities:r}})}(l,b):d&&(e=new g.Api.InputMediaContact({phoneNumber:d.phoneNumber,firstName:d.firstName,lastName:d.lastName,vcard:""}));await w;const f=e?g.Api.messages.SendMedia:g.Api.messages.SendMessage;await sn(new f({clearDraft:!0,message:s||"",entities:a?a.map(se):void 0,peer:J(n.id,n.accessHash),randomId:b,...u&&{silent:u},...p&&{scheduleDate:p},...i&&{replyToMsgId:i},...e&&{media:e},...h&&{noWebpage:h},...m&&{sendAs:J(m.id,m.accessHash)}}),!0)})(),ds}const gs={};async function ps(e){let{chat:t,message:n,text:s,entities:a,noWebPage:i,serverTimeOffset:o}=e;const r=1e3*n.date>Date.now()+1e3*o,c={content:{...n.content,...s&&{text:{text:s,entities:a}}}};rs({"@type":r?"updateScheduledMessage":"updateMessage",id:n.id,chatId:t.id,message:c}),C.localMessages[n.id]={...n,...c};const l=a&&a.map(se);await sn(new g.Api.messages.EditMessage({message:s||"",entities:l,peer:J(t.id,t.accessHash),id:n.id,...r&&{scheduleDate:n.date},...i&&{noWebpage:i}}),!0)}async function fs(e){let{chat:t,message:n,scheduledAt:s}=e;await sn(new g.Api.messages.EditMessage({peer:J(t.id,t.accessHash),id:n.id,scheduleDate:s}),!0)}async function hs(e,t,n){const{filename:s,blobUrl:a,mimeType:i,quick:o,voice:l}=t,d=await async function(e,t){const n=await async function(e){return(await fetch(e)).blob()}(e);return function(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}(n,t)}(a,s),u=t=>{n.isCanceled?u.isCanceled=!0:n(t,e.id)},p=await rn(d,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(l){const{duration:e,waveform:t}=l,{data:n}=R(t,63);f.push(new g.Api.DocumentAttributeAudio({voice:!0,duration:e,waveform:os.from(n)}))}return new g.Api.InputMediaUploadedDocument({file:p,mimeType:i,attributes:f})}async function ms(e){let{chat:t,messageId:n,isUnpin:s,isOneSide:a,isSilent:i}=e;await sn(new g.Api.messages.UpdatePinnedMessage({peer:J(t.id,t.accessHash),id:n,...s&&{unpin:!0},...a&&{pmOneside:!0},...i&&{silent:!0}}),!0)}async function _s(e){let{chat:t}=e;await sn(new g.Api.messages.UnpinAllMessages({peer:J(t.id,t.accessHash)}),!0)}async function ys(e){let{chat:t,messageIds:n,shouldDeleteForAll:s}=e;const a="channel"===j(t.id);await sn(a?new g.Api.channels.DeleteMessages({channel:X(t.id,t.accessHash),id:n}):new g.Api.messages.DeleteMessages({id:n,...s&&{revoke:!0}}))&&rs({"@type":"deleteMessages",ids:n,...a&&{chatId:t.id}})}async function bs(e){let{chat:t,messageIds:n}=e;await sn(new g.Api.messages.DeleteScheduledMessages({peer:J(t.id,t.accessHash),id:n}))&&rs({"@type":"deleteScheduledMessages",ids:n,chatId:t.id})}async function ws(e){let{chat:t,shouldDeleteForAll:n,maxId:s}=e;const a="channel"===j(t.id);await sn(a?new g.Api.channels.DeleteHistory({channel:X(t.id,t.accessHash),maxId:s}):new g.Api.messages.DeleteHistory({peer:J(t.id,t.accessHash),...n&&{revoke:!0},...!n&&{just_clear:!0},maxId:s}))&&rs({"@type":"deleteHistory",chatId:t.id})}async function vs(e){let{peer:t,messageIds:n,reason:s,description:a}=e;return await sn(new g.Api.messages.Report({peer:J(t.id,t.accessHash),id:n,reason:de(s),message:a}))}async function Is(e){let{peer:t,threadId:n,action:s}=e;const a=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}}(s);if(a)return await sn(new g.Api.messages.SetTyping({peer:J(t.id,t.accessHash),topMsgId:n,action:a}))}async function Cs(e){let{chat:t,threadId:n,maxId:s,serverTimeOffset:a}=e;const i="channel"===j(t.id);i&&-1===n?await sn(new g.Api.channels.ReadHistory({channel:X(t.id,t.accessHash),maxId:s})):i?await sn(new g.Api.messages.ReadDiscussion({peer:J(t.id,t.accessHash),msgId:n,readMaxId:s})):await sn(new g.Api.messages.ReadHistory({peer:J(t.id,t.accessHash),maxId:s})),-1===n?yn({chat:t,serverTimeOffset:a,noLastMessage:!0}):Ss({chat:t,threadId:n})}async function As(e){let{chat:t,messageIds:n}=e;const s="channel"===j(t.id);await sn(s?new g.Api.channels.ReadMessageContents({channel:X(t.id,t.accessHash),id:n}):new g.Api.messages.ReadMessageContents({id:n})),rs({...s?{"@type":"updateChannelMessages",channelId:t.id}:{"@type":"updateCommonBoxMessages"},ids:n,messageUpdate:{hasUnreadMention:!1,isMediaUnread:!1}})}async function Ss(e){let{chat:t,threadId:n}=e;const[s,a]=await Promise.all([sn(new g.Api.messages.GetDiscussionMessage({peer:J(t.id,t.accessHash),msgId:n})),sn(new g.Api.messages.GetReplies({peer:J(t.id,t.accessHash),msgId:n,offsetId:1,addOffset:-1,limit:1}))]);if(!s||!s.messages.length)return;const i=q(s.messages[0]);return i?(rs({"@type":"updateThreadInfo",chatId:i,threadId:n,threadInfo:{threadId:n,topMessageId:s.messages[s.messages.length-1].id,lastReadInboxMessageId:s.readInboxMaxId,messagesCount:a instanceof g.Api.messages.ChannelMessages?a.count:void 0},firstMessageId:a&&"messages"in a&&a.messages.length?a.messages[0].id:void 0}),s.chats.map((e=>Ke(e))).filter(Boolean).forEach((e=>{rs({"@type":"updateChat",id:e.id,chat:e,noTopChatsRequest:!0})})),{discussionChatId:i}):void 0}async function Ps(e){let t,{chat:n,type:s,query:a,topMessageId:i,minDate:o,maxDate:r,...c}=e;switch(s){case"media":t=new g.Api.InputMessagesFilterPhotoVideo;break;case"documents":t=new g.Api.InputMessagesFilterDocument;break;case"links":t=new g.Api.InputMessagesFilterUrl;break;case"audio":t=new g.Api.InputMessagesFilterMusic;break;case"voice":t=new g.Api.InputMessagesFilterRoundVoice;break;case"profilePhoto":t=new g.Api.InputMessagesFilterChatPhotos;break;default:t=new g.Api.InputMessagesFilterEmpty}const l=await sn(new g.Api.messages.Search({peer:J(n.id,n.accessHash),filter:t,q:a||"",topMsgId:i,minDate:o,maxDate:r,...c}));if(!l||l instanceof g.Api.messages.MessagesNotModified||!l.messages)return;xs(l);const d=l.chats.map((e=>Ke(e))).filter(Boolean),u=l.users.map(it).filter(Boolean),p=l.messages.map(_e).filter(Boolean);let f,h=p.length;return(l instanceof g.Api.messages.MessagesSlice||l instanceof g.Api.messages.ChannelMessages)&&(h=l.count,p.length&&(f=p[p.length-1].id)),{chats:d,users:u,messages:p,totalCount:h,nextOffsetId:f}}async function Ms(e){let t,{query:n,offsetRate:s=0,limit:a,type:i="text",minDate:o,maxDate:r}=e;switch(i){case"media":t=new g.Api.InputMessagesFilterPhotoVideo;break;case"documents":t=new g.Api.InputMessagesFilterDocument;break;case"links":t=new g.Api.InputMessagesFilterUrl;break;case"audio":t=new g.Api.InputMessagesFilterMusic;break;case"voice":t=new g.Api.InputMessagesFilterRoundVoice;break;default:if(!(n||r&&o))return;t=new g.Api.InputMessagesFilterEmpty}const c=await sn(new g.Api.messages.SearchGlobal({q:n,offsetRate:s,offsetPeer:new g.Api.InputPeerEmpty,limit:a,filter:t,folderId:0,minDate:o,maxDate:r}));if(!c||c instanceof g.Api.messages.MessagesNotModified||!c.messages)return;xs({chats:c.chats,users:c.users,messages:c.messages});const l=c.chats.map((e=>Ke(e))).filter(Boolean),d=c.users.map(it).filter(Boolean),u=c.messages.map(_e).filter(Boolean);let p,f=u.length;return(c instanceof g.Api.messages.MessagesSlice||c instanceof g.Api.messages.ChannelMessages)&&(f=c.count,u.length&&(p=u[u.length-1].id)),{messages:u,users:d,chats:l,totalCount:f,nextRate:"nextRate"in c&&c.nextRate?c.nextRate:p}}async function ks(e){let{message:t}=e;const n=await sn(new g.Api.messages.GetWebPagePreview({message:t}));return n&&De(n)}async function Rs(e){let{chat:t,messageId:n,options:s}=e;const{id:a,accessHash:i}=t;await sn(new g.Api.messages.SendVote({peer:J(a,i),msgId:n,options:s.map(W)}),!0)}async function Us(e){let{chat:t,messageId:n,option:s,offset:a,limit:i,shouldResetVoters:o}=e;const{id:r,accessHash:c}=t,l=await sn(new g.Api.messages.GetPollVotes({peer:J(r,c),id:n,...s&&{option:W(s)},...a&&{offset:a},...i&&{limit:i}}));if(!l)return;xs({chats:[],users:l.users,messages:[]});const d=l.users.map(it).filter(Boolean),u=l.votes.map((e=>({userId:e.userId,date:e.date})));return{count:l.count,votes:u,users:d,nextOffset:l.nextOffset,shouldResetVoters:o}}async function Es(e){let{fromChat:t,toChat:n,messages:s,serverTimeOffset:a,isSilent:i,scheduledAt:o,sendAs:r}=e;const c=s.map((e=>{let{id:t}=e;return t})),l=s.map(te);s.forEach(((e,t)=>{const s=function(e,t,n,s){const a=he++,{content:i,chatId:o,id:r,senderId:c,groupedId:l,isInAlbum:d}=t,u=i.audio,g=e.id===fe&&(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:fe,sendingState:"messageSendingStatePending",groupedId:l,isInAlbum:d,...c!==fe&&!u&&{forwardInfo:{date:t.date,isChannelPost:!1,fromChatId:o,fromMessageId:r,senderUserId:c}},...s&&{isScheduled:!0}}}(n,e,a,o);C.localMessages[String(l[t])]=s,rs({"@type":s.isScheduled?"newScheduledMessage":"newMessage",id:s.id,chatId:n.id,message:s})})),await sn(new g.Api.messages.ForwardMessages({fromPeer:J(t.id,t.accessHash),toPeer:J(n.id,n.accessHash),randomId:l,id:c,...i&&{sil2ent:i},...o&&{scheduleDate:o},...r&&{sendAs:J(r.id,r.accessHash)}}),!0)}async function Ds(e){let{chat:t,timestamp:n}=e;const s=await sn(new g.Api.messages.GetHistory({peer:J(t.id,t.accessHash),offsetDate:n,addOffset:-1,limit:1}));if(s&&!(s instanceof g.Api.messages.MessagesNotModified)&&s.messages&&s.messages.length)return s.messages[0].id}async function Bs(e){let{chat:t}=e;const{id:n,accessHash:s}=t,a=await sn(new g.Api.messages.GetScheduledHistory({peer:J(n,s)}));if(a&&!(a instanceof g.Api.messages.MessagesNotModified)&&a.messages)return xs(a),{messages:a.messages.map(_e).filter(Boolean)}}async function Ts(e){let{chat:t,ids:n}=e;const{id:s,accessHash:a}=t;await sn(new g.Api.messages.SendScheduledMessages({peer:J(s,a),id:n}),!0)}function xs(e){K(e.users),K(e.chats),e.messages.forEach((e=>{(e instanceof g.Api.Message&&ae(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 Vs(e){let{chat:t}=e;const n=await sn(new g.Api.messages.Search({peer:J(t.id,t.accessHash),filter:new g.Api.InputMessagesFilterPinned,q:"",limit:50}));if(!n||n instanceof g.Api.messages.MessagesNotModified||!n.messages)return;xs(n);const s=n.chats.map((e=>Ke(e))).filter(Boolean),a=n.users.map(it).filter(Boolean);return{messages:n.messages.map(_e).filter(Boolean),users:a,chats:s}}async function Ns(e){let{chat:t,messageId:n}=e;const s=await sn(new g.Api.messages.GetMessageReadParticipants({peer:J(t.id,t.accessHash),msgId:n}));return s?s.map(String):void 0}async function Fs(e){let{chat:t}=e;const n=await sn(new g.Api.channels.GetSendAs({peer:J(t.id,t.accessHash)}));if(n)return K(n.users),K(n.chats),{users:n.users.map(it).filter(Boolean),chats:n.chats.map((e=>Ke(e))).filter(Boolean),ids:n.peers.map(F)}}function Ls(e){let{sendAs:t,chat:n}=e;return sn(new g.Api.messages.SaveDefaultSendAs({peer:J(n.id,n.accessHash),sendAs:J(t.id,t.accessHash)}))}async function qs(e){let{chat:t}=e;const n=await sn(new g.Api.channels.GetSponsoredMessages({channel:J(t.id,t.accessHash)}));if(n&&n.messages.length)return xs(n),{messages:n.messages.map(me).filter(Boolean),users:n.users.map(it).filter(Boolean),chats:n.chats.map((e=>Ke(e))).filter(Boolean)}}async function Os(e){let{chat:t,random:n}=e;await sn(new g.Api.channels.ViewSponsoredMessage({channel:J(t.id,t.accessHash),randomId:W(n)}))}let Hs,Gs,Ks,zs;async function Ws(e){let{id:t,accessHash:n}=e;const s=X(t,n);if(!(s instanceof g.Api.InputUser))return;const a=await sn(new g.Api.users.GetFullUser({id:s}));if(!a)return;const i=at(a);Hs({"@type":"updateUser",id:t,user:{fullInfo:i.fullInfo}})}async function js(e,t,n){const s=await sn(new g.Api.messages.GetCommonChats({userId:X(e,t),maxId:n?ue(n,j(n)):void 0,limit:100}));if(!s)return;sa(s);const a=[],i=[];return s.chats.forEach((e=>{const t=Ke(e);t&&(i.push(t),a.push(t.id))})),{chats:i,chatIds:a,isFullyLoaded:a.length<100}}async function $s(){const e=await sn(new g.Api.help.GetNearestDc);return null==e?void 0:e.country}async function Js(){const e=await sn(new g.Api.contacts.GetTopPeers({correspondents:!0}));if(!(e instanceof g.Api.contacts.TopPeers))return;const t=e.users.map(it).filter((e=>Boolean(e)&&!e.isSelf));return{ids:t.map((e=>{let{id:t}=e;return t})),users:t}}async function Qs(){const e=await sn(new g.Api.contacts.GetContacts({hash:E()("0")}));if(e&&!(e instanceof g.Api.contacts.ContactsNotModified))return e.users.forEach((e=>{e instanceof g.Api.User&&G(e,!0)})),{users:e.users.map(it).filter(Boolean),chats:e.users.map((e=>Ke(e))).filter(Boolean)}}async function Xs(e){let{users:t}=e;const n=await sn(new g.Api.users.GetUsers({id:t.map((e=>{let{id:t,accessHash:n}=e;return J(t,n)}))}));if(n&&n.length)return n.forEach((e=>{e instanceof g.Api.User&&G(e,!0)})),ct(n)}async function Zs(e){let{phone:t,firstName:n,lastName:s}=e;const a=await sn(new g.Api.contacts.ImportContacts({contacts:[ie({phone:t||"",firstName:n||"",lastName:s||""})]}));return a instanceof g.Api.contacts.ImportedContacts&&a.users.length&&G(a.users[0]),null!=a&&a.imported.length?N(a.imported[0].userId,"user"):void 0}function Ys(e){let{id:t,accessHash:n,phoneNumber:s="",firstName:a="",lastName:i="",shouldSharePhoneNumber:o=!1}=e;return sn(new g.Api.contacts.AddContact({id:X(t,n),firstName:a,lastName:i,phone:s,...o&&{addPhonePrivacyException:o}}),!0)}async function ea(e){let{id:t,accessHash:n}=e;const s=X(t,n);s instanceof g.Api.InputUser&&await sn(new g.Api.contacts.DeleteContacts({id:[s]}))&&Hs({"@type":"deleteContact",id:t})}async function ta(e,t){if(e){const{id:t,accessHash:n}=e,s=await sn(new g.Api.photos.GetUserPhotos({userId:X(t,n),limit:40,offset:0,maxId:E()("0")}));if(!s)return;return sa(s),{photos:s.photos.filter((e=>e instanceof g.Api.Photo)).map(v)}}const n=await Ps({chat: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 na(e){const{id:t,accessHash:n}=e;return sn(new g.Api.messages.ReportSpam({peer:J(t,n)}),!0)}function sa(e){"chats"in e&&K(e.chats),"photos"in e&&e.photos.forEach(H)}async function aa(e){let{hash:t="0"}=e;const n=await sn(new g.Api.messages.GetAllStickers({hash:E()(t)}));if(n&&!(n instanceof g.Api.messages.AllStickersNotModified))return n.sets.forEach((e=>{var t;null!==(t=e.thumbs)&&void 0!==t&&t.length&&(C.stickerSets[String(e.id)]=e)})),{hash:String(n.hash),sets:n.sets.map(M)}}async function ia(e){let{hash:t="0"}=e;const n=await sn(new g.Api.messages.GetRecentStickers({hash:E()(t)}));if(n&&!(n instanceof g.Api.messages.RecentStickersNotModified))return{hash:String(n.hash),stickers:wa(n.stickers.slice(0,20))}}async function oa(e){let{hash:t="0"}=e;const n=await sn(new g.Api.messages.GetFavedStickers({hash:E()(t)}));if(n&&!(n instanceof g.Api.messages.FavedStickersNotModified))return{hash:String(n.hash),stickers:wa(n.stickers)}}async function ra(e){let{hash:t="0"}=e;const n=await sn(new g.Api.messages.GetFeaturedStickers({hash:E()(t)}));if(n&&!(n instanceof g.Api.messages.FeaturedStickersNotModified))return{hash:String(n.hash),sets:n.sets.map(k)}}async function ca(e){let{sticker:t,unfave:n}=e;const s=new g.Api.messages.FaveSticker({id:Y(t),unfave:n});await sn(s)&&Gs({"@type":"updateFavoriteStickers"})}async function la(e){let{stickerSetShortName:t,stickerSetId:n,accessHash:s}=e;const a=await sn(new g.Api.messages.GetStickerSet({stickerset:n?Z(n,s):(i=t,new g.Api.InputStickerSetShortName({shortName:i}))}));var i,o;if(a instanceof g.Api.messages.StickerSet)return{set:M(a.set),stickers:wa(a.documents),packs:(o=a.packs,o.reduce(((e,t)=>{let{emoticon:n,documents:s}=t;return e[n]=s.map((e=>P(C.documents[String(e)]))).filter(Boolean),e}),{}))}}async function da(){const e=await sn(new g.Api.messages.GetStickerSet({stickerset:new g.Api.InputStickerSetAnimatedEmoji}));if(e instanceof g.Api.messages.StickerSet)return{set:M(e.set),stickers:wa(e.documents)}}async function ua(){const e=await sn(new g.Api.messages.GetStickerSet({stickerset:new g.Api.InputStickerSetAnimatedEmojiAnimations}));if(e instanceof g.Api.messages.StickerSet)return{set:M(e.set),stickers:wa(e.documents)}}async function ga(e){let{query:t,hash:n="0"}=e;const s=await sn(new g.Api.messages.SearchStickerSets({q:t,hash:E()(n)}));if(s&&!(s instanceof g.Api.messages.FoundStickerSetsNotModified))return{hash:String(s.hash),sets:s.sets.map(k)}}async function pa(e){let{hash:t="0"}=e;const n=await sn(new g.Api.messages.GetSavedGifs({hash:E()(t)}));if(n&&!(n instanceof g.Api.messages.SavedGifsNotModified))return{hash:String(n.hash),gifs:va(n.gifs)}}function fa(e){let{gif:t,shouldUnsave:n}=e;return sn(new g.Api.messages.SaveGif({id:Y(t),unsave:n}),!0)}async function ha(e){let{stickerSetId:t,accessHash:n}=e;await sn(new g.Api.messages.InstallStickerSet({stickerset:Z(t,n)}))&&Gs({"@type":"updateStickerSet",id:t,stickerSet:{installedDate:Date.now()}})}async function ma(e){let{stickerSetId:t,accessHash:n}=e;await sn(new g.Api.messages.UninstallStickerSet({stickerset:Z(t,n)}))&&Gs({"@type":"updateStickerSet",id:t,stickerSet:{installedDate:void 0}})}async function _a(e){let{query:t,offset:n=""}=e;if(!Ks){const e=await sn(new g.Api.help.GetConfig);if(!e)return;const t=await sn(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 s=await sn(new g.Api.messages.GetInlineBotResults({bot:Ks,peer:new g.Api.InputPeerEmpty,query:t,offset:n}));if(!s)return;const a=s.results.map((e=>{if(e instanceof g.Api.BotInlineMediaResult)return e.document})).filter(Boolean);return{nextOffset:s.nextOffset,gifs:va(a)}}async function ya(e){let{emoji:t,hash:n="0"}=e;const s=await sn(new g.Api.messages.GetStickers({emoticon:t,hash:E()(n)}));if(s&&!(s instanceof g.Api.messages.StickersNotModified))return{stickers:wa(s.stickers),hash:String(s.hash)}}async function ba(e){let{language:t,fromVersion:n}=e;const s=await sn(new g.Api.messages.GetEmojiKeywordsDifference({langCode:t,fromVersion:n}));if(s)return{language:s.langCode,version:s.version,keywords:s.keywords.reduce(((e,t)=>(e[t.keyword]=t.emoticons,e)),{})}}function wa(e){return e.map((e=>{if(e instanceof g.Api.Document){const t=P(e);if(t)return C.documents[String(e.id)]=e,t}})).filter(Boolean)}function va(e){return e.map((e=>{if(e instanceof g.Api.Document){const t=Me(e);if(t)return C.documents[String(e.id)]=e,t}})).filter(Boolean)}function Ia(e){let{username:t}=e;return sn(new g.Api.channels.CheckUsername({channel:new g.Api.InputChannelEmpty,username:t}))}async function Ca(e){let{chat:t,username:n}=e;await sn(new g.Api.channels.UpdateUsername({channel:X(t.id,t.accessHash),username:n}))&&zs({"@type":"updateChat",id:t.id,chat:{username:n}})}async function Aa(e){let{chat:t,usageLimit:n,expireDate:s}=e;const a=await sn(new g.Api.messages.ExportChatInvite({peer:J(t.id,t.accessHash),usageLimit:n,expireDate:s}));if(a)return zs({"@type":"updateChatFullInfo",id:t.id,fullInfo:{inviteLink:a.link}}),a.link}async function Sa(e){let{peer:t,admin:n,limit:s=0,isRevoked:a}=e;const i=await sn(new g.Api.messages.GetExportedChatInvites({peer:J(t.id,t.accessHash),adminId:X(n.id,n.accessHash),limit:s,revoked:a||void 0}));if(i)return K(i.users),i.invites.map(nt)}async function Pa(e){let{peer:t,isRevoked:n,link:s,expireDate:a,usageLimit:i,isRequestNeeded:o,title:r}=e;const c=await sn(new g.Api.messages.EditExportedChatInvite({link:s,peer:J(t.id,t.accessHash),expireDate:a,usageLimit:o?void 0:i,requestNeeded:o,title:r,revoked:n||void 0}));if(c){if(K(c.users),c instanceof g.Api.messages.ExportedChatInvite){const e=nt(c.invite);return{oldInvite:e,newInvite:e}}if(c instanceof g.Api.messages.ExportedChatInviteReplaced)return{oldInvite:nt(c.invite),newInvite:nt(c.newInvite)}}}async function Ma(e){let{peer:t,expireDate:n,usageLimit:s,isRequestNeeded:a,title:i}=e;const o=await sn(new g.Api.messages.ExportChatInvite({peer:J(t.id,t.accessHash),expireDate:n,usageLimit:a?void 0:s,requestNeeded:a||void 0,title:i}));if(o)return nt(o)}async function ka(e){let{peer:t,link:n}=e;return await sn(new g.Api.messages.DeleteExportedChatInvite({peer:J(t.id,t.accessHash),link:n}))}async function Ra(e){let{peer:t,admin:n}=e;return await sn(new g.Api.messages.DeleteRevokedExportedChatInvites({peer:J(t.id,t.accessHash),adminId:X(n.id,n.accessHash)}))}async function Ua(e){let{peer:t,link:n,offsetDate:s=0,offsetUser:a,limit:i=0,isRequested:o}=e;const r=await sn(new g.Api.messages.GetChatInviteImporters({peer:J(t.id,t.accessHash),link:n,offsetDate:s,offsetUser:a?X(a.id,a.accessHash):new g.Api.InputUserEmpty,limit:i,requested:o||void 0}));if(r)return K(r.users),r.importers.map((e=>function(e){const{userId:t,date:n,about:s,requested:a}=e;return{userId:N(t,"user"),date:n,about:s,isRequested:a}}(e)))}function Ea(e){let{peer:t,user:n,isApproved:s}=e;return sn(new g.Api.messages.HideChatJoinRequest({peer:J(t.id,t.accessHash),userId:X(n.id,n.accessHash),approved:s||void 0}),!0)}function Da(e){let{peer:t,isApproved:n,link:s}=e;return sn(new g.Api.messages.HideAllChatJoinRequests({peer:J(t.id,t.accessHash),approved:n||void 0,link:s}),!0)}function Ba(e){const{id:t,accessHash:n}=e;return sn(new g.Api.messages.HidePeerSettingsBar({peer:J(t,n)}))}const Ta={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"},xa={};let Va,Na,Fa;async function La(){const e=await sn(new g.Api.account.GetPassword);if(!e)return;const{hint:t,hasPassword:n}=e;return{hint:t,hasPassword:n}}function qa(e){return Va({"@type":"updateTwoFaStateWaitCode",length:e}),new Promise(((e,t)=>{xa.resolve=e,xa.reject=t}))}async function Oa(e){try{return await cn({isCheckPassword:!0,currentPassword:e}),!0}catch(e){return Wa(e),!1}}async function Ha(e){try{return await cn({currentPassword:e}),!0}catch(e){return Wa(e),!1}}async function Ga(e,t,n,s){try{return await cn({currentPassword:e,newPassword:t,hint:n,email:s,emailCodeCallback:qa,onEmailCodeError:Wa}),!0}catch(e){return Wa(e),!1}}async function Ka(e,t){try{return await cn({currentPassword:e,newPassword:e,email:t,emailCodeCallback:qa,onEmailCodeError:Wa}),!0}catch(e){return Wa(e),!1}}function za(e){xa.resolve(e)}function Wa(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=Ta[e.message];t||(t="Unexpected Error"),Va({"@type":"updateTwoFaError",message:t})}async function ja(e){let{call:t}=e;const n=await sn(new g.Api.phone.GetGroupCall({call:ge(t)}));if(!n)return;K(n.users),K(n.chats);const s=n.users.map(it).filter(Boolean),a=n.chats.map((e=>Ke(e))).filter(Boolean);return{groupCall:yt(n.call),users:s,chats:a}}function $a(e){let{call:t}=e;return sn(new g.Api.phone.DiscardGroupCall({call:ge(t)}),!0)}function Ja(e){let{call:t,participant:n,muted:s,presentationPaused:a,videoStopped:i,videoPaused:o,volume:r,raiseHand:c}=e;return sn(new g.Api.phone.EditGroupCallParticipant({call:ge(t),participant:J(n.id,n.accessHash),...void 0!==i&&{videoStopped:i},...void 0!==o&&{videoPaused:o},...void 0!==s&&{muted:s},...void 0!==a&&{presentationPaused:a},...void 0!==c&&{raiseHand:c},...void 0!==r&&{volume:r}}),!0)}function Qa(e){let{groupCall:t,title:n}=e;return sn(new g.Api.phone.EditGroupCallTitle({title:n,call:ge(t)}),!0)}async function Xa(e){let{call:t,canSelfUnmute:n}=e;const s=await sn(new g.Api.phone.ExportGroupCallInvite({canSelfUnmute:n||void 0,call:ge(t)}));if(s)return s.link}async function Za(e){let{call:t,offset:n}=e;const s=await sn(new g.Api.phone.GetGroupParticipants({call:ge(t),ids:[],sources:[],offset:n||"",limit:100}));if(!s)return;K(s.users),K(s.chats);const a=s.users.map(it).filter(Boolean),i=s.chats.map((e=>Ke(e))).filter(Boolean);return Na({"@type":"updateGroupCallParticipants",groupCallId:t.id,participants:s.participants.map(ht),nextOffset:s.nextOffset}),{users:a,chats:i}}function Ya(e){let{call:t}=e;return sn(new g.Api.phone.LeaveGroupCall({call:ge(t)}),!0)}async function ei(e){let{call:t,inviteHash:n,params:s}=e;const a=await sn(new g.Api.phone.JoinGroupCall({call:ge(t),joinAs:new g.Api.InputPeerSelf,muted:!0,videoStopped:!0,params:new g.Api.DataJSON({data:JSON.stringify(s)}),inviteHash:n}));if(a&&a instanceof g.Api.Updates){const e=a.updates.find((e=>e instanceof g.Api.UpdateGroupCall));if(!(e instanceof g.Api.UpdateGroupCall))return;return yt(e.call)}}async function ti(e){let{peer:t}=e;const n=(0,D.readBigIntFromBuffer)((0,D.generateRandomBytes)(4),!0,!0).toJSNumber(),s=await sn(new g.Api.phone.CreateGroupCall({peer:J(t.id,t.accessHash),randomId:n}));if(s&&s instanceof g.Api.Updates){const e=s.updates[0];if(e instanceof g.Api.UpdateGroupCall)return yt(e.call)}}function ni(e){let{call:t,params:n}=e;return sn(new g.Api.phone.JoinGroupCallPresentation({call:ge(t),params:new g.Api.DataJSON({data:JSON.stringify(n)})}),!0)}function si(e){let{call:t,subscribed:n}=e;return sn(new g.Api.phone.ToggleGroupCallStartSubscription({call:ge(t),subscribed:n}),!0)}function ai(e){let{call:t}=e;return sn(new g.Api.phone.LeaveGroupCallPresentation({call:ge(t)}),!0)}function ii(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((e=>{let{label:t,amount:n}=e;return{label:t,amount:Number(n.value)}}))})))}async function oi(e){let{chat:t,messageId:n,requestInfo:s,shouldSave:a}=e;const i=await sn(new g.Api.payments.ValidateRequestedInfo({peer:J(t.id,t.accessHash),msgId:n,save:a||void 0,info:ce(s)}));if(!i)return;const{id:o,shippingOptions:r}=i;return o?{id:o,shippingOptions:ii(r)}:void 0}async function ri(e){let{chat:t,messageId:n,formId:s,requestedInfoId:a,shippingOptionId:i,credentials:o}=e;const r=await sn(new g.Api.payments.SendPaymentForm({formId:E()(s),peer:J(t.id,t.accessHash),msgId:n,requestedInfoId:a,shippingOptionId:i,credentials:new g.Api.InputPaymentCredentials({save:o.save,data:new g.Api.DataJSON({data:JSON.stringify(o.data)})})}));if(!(r instanceof g.Api.payments.PaymentVerificationNeeded))return Boolean(r);Fa({"@type":"updatePaymentVerificationNeeded",url:r.url})}async function ci(e){let{chat:t,messageId:n}=e;const s=await sn(new g.Api.payments.GetPaymentForm({peer:J(t.id,t.accessHash),msgId:n}));if(s)return function(e){const{formId:t,canSaveCredentials:n,passwordMissing:s,providerId:a,nativeProvider:i,nativeParams:o,savedInfo:r,invoice:c}=e,{test:l,nameRequested:d,phoneRequested:u,emailRequested:g,shippingAddressRequested:p,flexible:f,phoneToProvider:h,emailToProvider:m,currency:_,prices:y}=c,b=y.map((e=>{let{label:t,amount:n}=e;return{label:t,amount:Number(n.value)}})),w=o?JSON.parse(o.data):{};return{canSaveCredentials:n,passwordMissing:s,formId:String(t),providerId:String(a),nativeProvider:i,savedInfo:r,invoice:{test:l,nameRequested:d,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,publicToken:null==w?void 0:w.public_token}}}(s)}async function li(e,t){const n=await sn(new g.Api.payments.GetPaymentReceipt({peer:J(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:l}=n||{},{prices:d}=t,u=d.map((e=>{let{label:t,amount:n}=e;return{label:t,amount:Number(n.value)}}));let g,p;return s&&(g=s.prices.map((e=>{let{label:t,amount:n}=e;return{label:t,amount:Number(n.value)}})),p=s.title),{currency:a,prices:u,info:{shippingAddress:r,phone:c,name:l},totalAmount:Number(i.value),credentialsTitle:o,shippingPrices:g,shippingMethod:p}}(n)}var di=n(8764).Buffer;function ui(e){const{emojies_sounds:t}=e;return Object.keys(t).reduce(((e,n)=>{const s=t[n];return C.documents[s.id]=new g.Api.Document({id:E()(s.id),accessHash:E()(s.access_hash),dcId:1,mimeType:"audio/ogg",fileReference:di.from(atob(s.file_reference_base64.replace(/-/g,"+").replace(/_/g,"/")))}),e[n]=s.id,e}),{})}const gi=["ar","fa","id","ko","uz"];function pi(e){let{firstName:t,lastName:n,about:s}=e;return sn(new g.Api.account.UpdateProfile({firstName:t||"",lastName:n||"",about:s||""}),!0)}function fi(e){return sn(new g.Api.account.CheckUsername({username:e}))}function hi(e){return sn(new g.Api.account.UpdateUsername({username:e}),!0)}async function mi(e){const t=await rn(e);return sn(new g.Api.photos.UploadProfilePhoto({file:t}),!0)}async function _i(e){const t=await rn(e);await sn(new g.Api.photos.UploadProfilePhoto({file:t}))}async function yi(){const e=await sn(new g.Api.account.GetWallPapers({hash:E()("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=>{C.documents[String(e.document.id)]=e.document})),{wallpapers:t.map(lt).filter(Boolean)}}async function bi(e){const t=await rn(e),n=await sn(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=lt(n);return s?(C.documents[String(n.document.id)]=n.document,{wallpaper:s}):void 0}async function wi(){const e=await sn(new g.Api.contacts.GetBlocked({limit:100}));if(e)return Oi(e),{users:e.users.map(it).filter(Boolean),chats:e.chats.map((e=>Ke(e,void 0,!0))).filter(Boolean),blockedIds:e.blocked.map((e=>F(e.peerId))),totalCount:e instanceof g.Api.contacts.BlockedSlice?e.count:e.blocked.length}}function vi(e,t){return sn(new g.Api.contacts.Block({id:J(e,t)}))}function Ii(e,t){return sn(new g.Api.contacts.Unblock({id:J(e,t)}))}async function Ci(){const e=await sn(new g.Api.account.GetAuthorizations);if(e)return e.authorizations.map(dt)}function Ai(e){return sn(new g.Api.account.ResetAuthorization({hash:E()(e)}))}function Si(){return sn(new g.Api.auth.ResetAuthorizations)}async function Pi(e){let{serverTimeOffset:t}=e;const n=await sn(new g.Api.account.GetNotifyExceptions({compareSound:!0}),void 0,void 0,!0);if(n instanceof g.Api.Updates||n instanceof g.Api.UpdatesCombined)return Oi(n),n.updates.reduce(((e,n)=>n instanceof g.Api.UpdateNotifySettings&&n.peer instanceof g.Api.NotifyPeer?(e.push(gt(n.notifySettings,n.peer.peer,t)),e):e),[])}async function Mi(e){let{serverTimeOffset:t}=e;const[n,s,a,i]=await Promise.all([sn(new g.Api.account.GetContactSignUpNotification),sn(new g.Api.account.GetNotifySettings({peer:new g.Api.InputNotifyUsers})),sn(new g.Api.account.GetNotifySettings({peer:new g.Api.InputNotifyChats})),sn(new g.Api.account.GetNotifySettings({peer:new g.Api.InputNotifyBroadcasts}))]);if(!s||!a||!i)return!1;const{silent:o,muteUntil:r,showPreviews:c}=s,{silent:l,muteUntil:d,showPreviews:u}=a,{silent:p,muteUntil:f,showPreviews:h}=i;return{hasContactJoinedNotifications:!n,hasPrivateChatsNotifications:!(o||"number"==typeof r&&Fe(t)sn(new g.Api.langpack.GetLangPack({langPack:e,langCode:gi.includes(n)?`${n}-raw`:n})))))).filter(Boolean).map((e=>p(e.strings.map(_),"key")));if(s.length)return{langPack:Object.assign({},...s.reverse())}}async function Di(e){let{langPack:t,langCode:n,keys:s}=e;const a=await sn(new g.Api.langpack.GetStrings({langPack:t,langCode:gi.includes(n)?`${n}-raw`:n,keys:s}));if(a)return a.map(_)}async function Bi(e){const t=le(e),n=await sn(new g.Api.account.GetPrivacy({key:t}));if(n)return Oi(n),ut(n.rules)}function Ti(e){const t=Xt.session.getAuthKey().getKey();return sn(new g.Api.account.RegisterDevice({tokenType:10,secret:t,appSandbox:!1,otherUids:[],token:e}))}function xi(e){return sn(new g.Api.account.UnregisterDevice({tokenType:10,otherUids:[],token:e}))}async function Vi(e,t){const n=le(e),s=[];switch(t.allowedUsers&&s.push(new g.Api.InputPrivacyValueAllowUsers({users:t.allowedUsers.map((e=>{let{id:t,accessHash:n}=e;return X(t,n)}))})),t.allowedChats&&s.push(new g.Api.InputPrivacyValueAllowChatParticipants({chats:t.allowedChats.map((e=>{let{id:t}=e;return X(t)}))})),t.blockedUsers&&s.push(new g.Api.InputPrivacyValueDisallowUsers({users:t.blockedUsers.map((e=>{let{id:t,accessHash:n}=e;return X(t,n)}))})),t.blockedChats&&s.push(new g.Api.InputPrivacyValueDisallowChatParticipants({chats:t.blockedChats.map((e=>{let{id:t}=e;return X(t)}))})),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 sn(new g.Api.account.SetPrivacy({key:n,rules:s}));if(a)return Oi(a),ut(a.rules)}async function Ni(e){await sn(new g.Api.account.UpdateStatus({offline:!e}))}async function Fi(){const e=await sn(new g.Api.account.GetContentSettings);if(e)return{isSensitiveEnabled:Boolean(e.sensitiveEnabled),canChangeSensitive:Boolean(e.sensitiveCanChange)}}function Li(e){return sn(new g.Api.account.SetContentSettings({sensitiveEnabled:e||void 0}))}async function qi(){const e=await sn(new g.Api.help.GetAppConfig);if(e)return function(e){const t=ft(e);return{emojiSounds:ui(t),defaultReaction:t.reactions_default,seenByMaxChatMembers:t.chat_read_mark_size_threshold,seenByExpiresAt:t.chat_read_mark_expire_period}}(e)}function Oi(e){K(e.users),K(e.chats)}async function Hi(e){let{langCode:t="en"}=e;const n=await sn(new g.Api.help.GetCountriesList({langCode:t}));if(n instanceof g.Api.help.CountriesList)return s=n.countries,{phoneCodes:(a=s.filter((e=>!e.hidden)).map((e=>e.countryCodes.map((t=>pt(e,t))))),a.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:s.filter((e=>!e.hidden)).map((e=>pt(e))).sort(((e,t)=>e.name?e.name.localeCompare(t.name):e.defaultName.localeCompare(t.defaultName)))};var s,a}function Gi(e){return e?f(e,["url","mimeType"]):void 0}async function Ki(e){let{chatId:t,accessHash:n,messageId:s,data:a}=e;const i=await sn(new g.Api.messages.GetBotCallbackAnswer({peer:J(t,n),msgId:s,data:W(a)}));return i?_(i):void 0}async function zi(){const e=await sn(new g.Api.contacts.GetTopPeers({botsInline:!0}));if(!(e instanceof g.Api.contacts.TopPeers))return;const t=e.users.map(it).filter(Boolean);return{ids:t.map((e=>{let{id:t}=e;return t})),users:t}}async function Wi(e){let{username:t}=e;const n=await sn(new g.Api.contacts.ResolveUsername({username:t}));if(n&&n.users[0]instanceof g.Api.User&&n.users[0].bot&&n.users[0].botInlinePlaceholder)return G(n.users[0]),{user:it(n.users[0]),chat:Ke(n.users[0])}}async function ji(e){let{bot:t,chat:n,query:s,offset:a=""}=e;const i=await sn(new g.Api.messages.GetInlineBotResults({bot:J(t.id,t.accessHash),peer:J(n.id,n.accessHash),query:s,offset:a}));var o,r,c,l,d;if(i)return K(i.users),{isGallery:Boolean(i.gallery),help:t.botPlaceholder,nextOffset:(l=t.username,d=i.nextOffset,"gif"===l&&"0"===d?"":d),switchPm:(c=i.switchPm,c?f(c,["text","startParam"]):void 0),users:i.users.map(it).filter(Boolean),results:(o=String(i.queryId),r=i.results,r.map((e=>{return e instanceof g.Api.BotInlineMediaResult?(e.document instanceof g.Api.Document&&(t=e.document,C.documents[String(t.id)]=t),e.photo instanceof g.Api.Photo&&(n=e.photo,C.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:P(r)},...o instanceof g.Api.Photo&&{photo:v(o)},..."gif"===s&&r instanceof g.Api.Document&&{gif:Me(r)},..."video"===s&&r instanceof g.Api.Document&&{thumbnail:w(r.thumbs)}}}(e,o)):(e.thumb&&(s=e.thumb,C.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:Gi(r)}}(e,o));var t,n,s})))}}async function $i(e){let{chat:t,resultId:n,queryId:s,replyingTo:a,sendAs:i,isSilent:o,scheduleDate:r}=e;const c=te();await sn(new g.Api.messages.SendInlineBotResult({clearDraft:!0,randomId:c,queryId:E()(s),peer:J(t.id,t.accessHash),id:n,scheduleDate:r,...o&&{silent:!0},...a&&{replyToMsgId:a},...i&&{sendAs:J(i.id,i.accessHash)}}),!0)}async function Ji(e){let{bot:t,startParam:n}=e;const s=te();await sn(new g.Api.messages.StartBot({bot:J(t.id,t.accessHash),peer:J(t.id,t.accessHash),randomId:s,startParam:n}),!0)}function Qi(e){let{chat:t,emoticon:n}=e;return sn(new g.Api.messages.SetTyping({peer:J(t.id,t.accessHash),action:new g.Api.SendMessageEmojiInteractionSeen({emoticon:n})}))}function Xi(e){let{chat:t,emoticon:n,messageId:s,timestamps:a}=e;return sn(new g.Api.messages.SetTyping({peer:J(t.id,t.accessHash),action:new g.Api.SendMessageEmojiInteraction({emoticon:n,msgId:s,interaction:new g.Api.DataJSON({data:JSON.stringify({v:1,a:a.map((e=>({t:e,i:1})))})})})}))}async function Zi(){const e=await sn(new g.Api.messages.GetAvailableReactions({}));if(e&&!(e instanceof g.Api.messages.AvailableReactionsNotModified))return e.reactions.forEach((e=>{e.staticIcon instanceof g.Api.Document&&(C.documents[String(e.staticIcon.id)]=e.staticIcon),e.selectAnimation instanceof g.Api.Document&&(C.documents[String(e.selectAnimation.id)]=e.selectAnimation),e.aroundAnimation instanceof g.Api.Document&&(C.documents[String(e.aroundAnimation.id)]=e.aroundAnimation),e.centerIcon instanceof g.Api.Document&&(C.documents[String(e.centerIcon.id)]=e.centerIcon)})),e.reactions.map(Ie)}function Yi(e){let{chat:t,messageId:n,reaction:s}=e;return sn(new g.Api.messages.SendReaction({...s&&{reaction:s},peer:J(t.id,t.accessHash),msgId:n}),!0)}function eo(e){let{ids:t,chat:n}=e;return sn(new g.Api.messages.GetMessagesReactions({id:t,peer:J(n.id,n.accessHash)}),!0)}async function to(e){let{chat:t,messageId:n,reaction:s,offset:a}=e;const i=await sn(new g.Api.messages.GetMessageReactionsList({peer:J(t.id,t.accessHash),id:n,...s&&{reaction:s},limit:100,...a&&{offset:a}}));if(!i)return;K(i.users);const{nextOffset:o,reactions:r,count:c}=i;return{users:i.users.map(it).filter(Boolean),nextOffset:o,reactions:r.map(ve),count:c}}function no(e){let{reaction:t}=e;return sn(new g.Api.messages.SetDefaultReaction({reaction:t}))}function so(e,t){if(e.error)throw new Error(e.error);const n=JSON.parse(e.json.data),[s,...a]=n.columns,i=n.y_scaled;return{type:t?"area":n.types.y0,zoomToken:e.zoomToken,labelFormatter:n.xTickFormatter,tooltipFormatter:n.xTooltipFormatter,labels:s.slice(1),hideCaption:!n.subchart.show,hasSecondYAxis:i,isStacked:n.stacked&&!i,isPercentage:t,datasets:a.map((e=>{const t=e[0];return{name:n.names[t],color:(s=n.colors[t],s.substring(s.indexOf("#"))),values:e.slice(1)};var s})),...ao(n.subchart.defaultZoom,s.slice(1))}}function ao(e,t){const[n,s]=e;let a=0,i=t.length-1;return t.forEach(((e,t)=>{!a&&e>=n&&(a=t),!i&&e>=s&&(i=t)})),{minimapRange:{begin:Math.max(0,a/(t.length-1)),end:Math.min(1,i/(t.length-1))},labelFromIndex:a,labelToIndex:i}}function io(e){let{current:t,previous:n}=e;const s=t-n;return{current:t,change:s,...n&&{percentage:(s?Math.abs(s)/n*100:0).toFixed(2)}}}async function oo(e){let{chat:t}=e;const n=await sn(new g.Api.stats.GetBroadcastStats({channel:X(t.id,t.accessHash)}),void 0,void 0,void 0,t.fullInfo.statisticsDcId);var s,a;if(n)return{growthGraph:so((s=n).growthGraph),followersGraph:so(s.followersGraph),muteGraph:so(s.muteGraph),topHoursGraph:so(s.topHoursGraph),languagesGraph:s.languagesGraph.token,viewsBySourceGraph:s.viewsBySourceGraph.token,newFollowersBySourceGraph:s.newFollowersBySourceGraph.token,interactionsGraph:s.interactionsGraph.token,followers:io(s.followers),viewsPerPost:io(s.viewsPerPost),sharesPerPost:io(s.sharesPerPost),enabledNotifications:(a=s.enabledNotifications,{percentage:(a.part/a.total*100).toFixed(2)}),recentTopMessages:s.recentMessageInteractions}}async function ro(e){let{chat:t}=e;const n=await sn(new g.Api.stats.GetMegagroupStats({channel:X(t.id,t.accessHash)}),void 0,void 0,void 0,t.fullInfo.statisticsDcId);var s,a;if(n)return{growthGraph:so((s=n).growthGraph),membersGraph:so(s.membersGraph),topHoursGraph:so(s.topHoursGraph),languagesGraph:s.languagesGraph.token,messagesGraph:s.messagesGraph.token,actionsGraph:s.actionsGraph.token,period:(a=s.period,{maxDate:a.maxDate,minDate:a.minDate}),members:io(s.members),viewers:io(s.viewers),messages:io(s.messages),posters:io(s.posters)}}async function co(e){let{token:t,x:n,isPercentage:s,dcId:a}=e;const i=await sn(new g.Api.stats.LoadAsyncGraph({token:t,...n&&{x:E()(n)}}),void 0,void 0,void 0,a);if(i)return so(i,s)}let lo;async function uo(e,t){lo=e,function(e){bt=e}(mo),function(e){Mt=e}(mo),function(e){gn=e}(mo),function(e){rs=e}(mo),function(e){Hs=e}(mo),function(e){Gs=e}(mo),function(e){zs=e}(mo),function(e){Va=e}(mo),function(e){Na=e}(mo),function(e){Fa=e}(mo),await async function(e,t){Qt=e;const{userAgent:n,platform:s,sessionData:a,isTest:i,isMovSupported:o,isWebmSupported:r}=t,c=new g.sessions.CallbackSession(a,tn);self.isMovSupported=o,self.isWebmSupported=r,Xt=new g.TelegramClient(c,"2496","8da85b0d5bfe62527e5b244c209159c3",{deviceModel:navigator.userAgent||n||"Unknown UserAgent",systemVersion:s||"Unknown platform",appVersion:"1.38.2 Z",useWSS:!0,additionalDcsDisabled:!1,testServers:i}),Xt.addEventHandler(nn,Jt),Xt.addEventHandler(At,Jt);try{try{await Xt.start({phoneNumber:kt,phoneCode:Rt,password:Ut,firstAndLastNames:Et,qrCode:Dt,onError:Bt,initialMethod:"iOS"===s||"Android"===s?"phoneNumber":"qrCode"})}catch(e){if(console.error(e),"Disconnect"!==e.message)return void Qt({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}Mt(Tt("authorizationStateReady")),tn(c.getSessionData()),Qt({"@type":"updateApiReady"}),ln()}catch(e){throw e}}(mo,t)}const go=function(e,t){let n,s=!1;return function(){for(var a=arguments.length,i=new Array(a),o=0;o{s=!1,t(...n)})))}}((function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];d?t?u.push(e):d.push(e):(d=t?[]:[e],u=t?[e]:[],Promise.resolve().then((()=>{const e=d,t=u;d=void 0,u=void 0,t.forEach((e=>e())),e.forEach((e=>e()))})))}),(function(e){if(!ho||e!==fo)return;const t=ho;ho=void 0,t.forEach(lo)}));let po,fo,ho;function mo(e){ho?ho.push(e):ho=[e],po&&!o.has(e["@type"])||(po=function(e,t){let n,s,a,i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function(){s=!0;for(var o=arguments.length,r=new Array(o),c=0;c{if(!s)return self.clearInterval(n),void(n=void 0);s=!1,e(...a)}),t))}}(go,i,!0),fo=Math.random()),po(fo)}self.onerror=e=>{console.error(e),bo({type:"unhandledError",error:{message:e.error.message||"Uncaught exception in worker"}})},self.addEventListener("unhandledrejection",(e=>{console.error(e),bo({type:"unhandledError",error:{message:e.reason.message||"Uncaught rejection in worker"}})}));const _o=new Map;function yo(e){bo({type:"update",update:e})}function bo(e,t){t?postMessage(e,[t]):postMessage(e)}onmessage=async e=>{const{data:t}=e;switch(t.type){case"initApi":await uo(yo,t.args[0]);break;case"callMethod":{const{messageId:e,name:n,args:s}=t;try{if(e){const t=function(){for(var t=arguments.length,n=new Array(t),s=0;s1?t-1:0),s=1;s{var s=n(8764).Buffer;const a=n(4736),i=n(6842);function o(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],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){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;const n=a(e),i=[];for(let e=0;e2&&void 0!==arguments[2])||arguments[2],i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const o=(e=a(e)).bitLength(),r=Math.ceil(o/8);if(t0&&void 0!==arguments[0])||arguments[0];return o(l(8),!0,e)},mod:function(e,t){return(e%t+t)%t},crc32:function(e){u||(u=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},generateRandomBytes:l,generateKeyDataFromNonce:async function(e,t){e=r(e,16),t=r(t,32);const[n,a,i]=await Promise.all([d(s.concat([t,e])),d(s.concat([e,t])),d(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:d,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){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[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:l,modExp:d,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=d(a(b),t,g);if(m(n,g)){const e=h(n),i=o(await c(s.concat([e,A])),!1);if(i.greater(a(0)))return[t,e,i]}}})(),E=l(w.subtract(M),g);if(!m(E,g))throw new Error("bad gB");const D=U.multiply(v),B=k.add(D),T=d(E,B,g),[x,V,N,F,L]=await Promise.all([c(h(T)),c(I),c(C),c(n.salt1),c(n.salt2)]),q=await c(s.concat([_(V,N),F,L,R,A,x]));return new i.InputCheckPasswordSRP({srpId:e.srpId,A:s.from(R),M1:q})},computeDigest:async function(e,t){try{p(e.p,e.g)}catch(e){throw new Error("bad p/g in password")}return h(d(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){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],s=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];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){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[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:()=>d});var s=n(7150),a=n.n(s),i=n(9618),o=n(9674),r=n(7873),c=n.n(r),l=n(8764).Buffer;async function d(e,t){let{isCheckPassword:n,currentPassword:s,newPassword:r,hint:d="",email:u,emailCodeCallback:g,onEmailCodeError:p}=t;if(!r&&!s)throw new Error("Neither `currentPassword` nor `newPassword` is present");if(u&&(!g||!p))throw new Error("`email` present without `emailCodeCallback` and `onEmailCodeError`");const f=await e.invoke(new(a().account.GetPassword));f.newAlgo instanceof a().PasswordKdfAlgoUnknown||(f.newAlgo.salt1=l.concat([f.newAlgo.salt1,(0,i.generateRandomBytes)(32)])),!f.hasPassword&&s&&(s=void 0);const h=s?await(0,o.computeCheck)(f,s):new(a().InputCheckPasswordEmpty);if(n)await e.invoke(new(a().auth.CheckPassword)({password:h}));else try{await e.invoke(new(a().account.UpdatePasswordSettings)({password:h,newSettings:new(a().account.PasswordInputSettings)({newAlgo:f.newAlgo,newPasswordHash:r?await(0,o.computeDigest)(f.newAlgo,r):l.alloc(0),hint:d,email:u,newSecureSettings:void 0})}))}catch(t){if(!(t instanceof c().EmailUnconfirmedError))throw t;for(;;)try{const n=await g(t.codeLength);if(!n)throw new Error("Code is empty");await e.invoke(new(a().account.ConfirmPasswordEmail)({code:n}));break}catch(e){p(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),l=n(9618),d=n(8960),u=n(9270),{LAYER:g}=n(845),{constructors:p,requests:f}=n(7404),{ConnectionTCPObfuscated:h,MTProtoSender:m,UpdateConnectionState:_}=n(8415),{authFlow:y,checkAuthorization:b}=n(1545),{downloadFile:w}=n(2288),{uploadFile:v}=n(4766),{updateTwoFaSettings:I}=n(243),C=131072,A=["w","y","d","x","c","m","b","a","s"];class S{constructor(e,t,n){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:S.DEFAULT_OPTIONS;if(!t||!n)throw Error('Your API ID or Hash are invalid. Please read "Requirements" on README.md');const o={...S.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._isSwitchingDc=!1,this._destroyed=!1}async connect(){await this._initSession(),void 0===this._sender&&(this._sender=new m(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.isReconnecting=!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._isSwitchingDc=!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(){let e;for(;!this._destroyed;)if(await l.sleep(3e3),this._sender.isReconnecting||this._isSwitchingDc)e=void 0;else{try{const t=()=>this._sender.send(new f.PingDelayDisconnect({pingId:l.getRandomInt(Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER),disconnectDelay:6e4})),n=Date.now(),s=e?n-e:void 0;if(!s||s<5e3)await U((()=>R(t,5e3)),3,100);else{let e=setTimeout((()=>{this._handleUpdate(new _(_.disconnected)),e=void 0}),1e3);await R(t,3e3),e&&(clearTimeout(e),e=void 0),this._handleUpdate(new _(_.connected))}e=Date.now()}catch(t){if(console.warn(t),e=void 0,this._sender.isReconnecting||this._isSwitchingDc)continue;await this.disconnect(),await this.connect()}if((new Date).getTime()-this._lastRequest>18e5){try{await this.invoke(new f.updates.GetState)}catch(e){}e=void 0}}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=d.getDC(e);return this.session.setDC(e,t.ipAddress,t.port),await this._sender.authKey.setKey(void 0),this.session.setAuthKey(void 0),this._isSwitchingDc=!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=d.getDC(t,Boolean(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 l.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 l.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 m(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){return w(this,e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}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){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[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:d.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=A.indexOf(t);se.type===A[s])),n)return n}_downloadCachedPhotoSize(e){let t;return t=e instanceof p.PhotoStrippedSize?d.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:C}),a=await this._borrowExportedSender(4),i=await a.send(s);if(n+=131072,!i.bytes.length)break;if(t.push(i.bytes),i.bytes.length0&&void 0!==arguments[0]?arguments[0]:{update:void 0,others:void 0,channelId:void 0,ptsDate:void 0};for(const[t,n]of this._eventBuilders){const s=t.build(e.update);s&&await n(s)}}isConnected(){return!(!this._sender||!this._sender.isConnected())}}var P,M,k;function R(e,t){return Promise.race([e(),l.sleep(t).then((()=>Promise.reject(new Error("TIMEOUT"))))])}async function U(e,t,n){for(let s=0;s{"use strict";n.r(t),n.d(t,{authFlow:()=>d,checkAuthorization:()=>u});var s=n(7150),a=n.n(s),i=n(8960),o=n.n(i),r=n(9618),c=n(9674);const l="phoneNumber";async function d(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=l}=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,l=!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 d=await e.invoke(new(a().auth.SignIn)({phoneNumber:s,phoneCodeHash:i,phoneCode:o}));if(d instanceof a().auth.AuthorizationSignUpRequired){l=!0,c=d.termsOfService;break}return d.user}catch(t){if("SESSION_PASSWORD_NEEDED"===t.message)return h(e,0,n);n.onError(t)}if(l)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){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];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),l=n(8764).Buffer;function d(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,d(this,"deferred",void 0),d(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:d,workers:p=1}=n,{dcId:f,progressCallback:h,start:m=0}=n;r=r&&r{for(;;){let l;try{l=await e.getSender(f);const o=await l.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");C+=1/y,h(C)}return!r&&o.bytes.lengthr)break}const A=(await Promise.all(w)).filter(Boolean),S=r?r+1-m:void 0;return l.concat(A,S)}},4766:(e,t,n)=>{"use strict";n.r(t),n.d(t,{uploadFile:()=>d});var s=n(7150),a=n.n(s),i=n(9618),o=n(8960),r=n(7873),c=n.n(r),l=n(8764).Buffer;async function d(e,t){const{file:n,onProgress:s}=t;let{workers:r}=t;const{name:d,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=l.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:d}):new(a().InputFile)({id:g,parts:h,name:d,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:l}=n(9618);class d{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 d)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 l(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)])]),l=(await a(c)).slice(4,20);return r(l,!0,!0)}equals(e){return e instanceof this.constructor&&this._key&&e.getKey()&&e.getKey().equals(this._key)}}e.exports=d},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,l=s.one,d=s.one,u=s.zero,g=s.zero;for(;c.eq(s.one);){u=t;for(let i=0;s(i).lesser(l);i++)t=a(t,s(2),e).add(n).remainder(e);for(r=s.zero;r.lesser(l)&&c.eq(s.one);){g=t;const p=s.min(o,l.minus(r));for(let i=0;s(i).lesser(p);i++)t=a(t,s(2),e).add(n).remainder(e),d=d.multiply(u.minus(t).abs()).remainder(e);c=i.gcd(d,e),r=r.add(o)}l=l.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 d=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;el,ab2iBig:()=>o,ab2iLow:()=>i,i2ab:()=>c,i2abBig:()=>a,i2abLow:()=>s,isBigEndian:()=>r});const r=1===new Uint8Array(new Uint32Array([16909060]))[0],c=r?a:s,l=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 l{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;n2&&void 0!==arguments[2]?arguments[2]:e;for(let s=0;sa,s2i:()=>s,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(){for(var e=arguments.length,t=new Array(e),n=0;n{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){let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;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(){super(...arguments),t(this,"code",400),t(this,"message","BAD_REQUEST")}},UnauthorizedError:class extends n{constructor(){super(...arguments),t(this,"code",401),t(this,"message","UNAUTHORIZED")}},ForbiddenError:class extends n{constructor(){super(...arguments),t(this,"code",403),t(this,"message","FORBIDDEN")}},NotFoundError:class extends n{constructor(){super(...arguments),t(this,"code",404),t(this,"message","NOT_FOUND")}},AuthKeyError:class extends n{constructor(){super(...arguments),t(this,"code",406),t(this,"message","AUTH_KEY")}},FloodError:class extends n{constructor(){super(...arguments),t(this,"code",420),t(this,"message","FLOOD")}},ServerError:class extends n{constructor(){super(...arguments),t(this,"code",500),t(this,"message","INTERNAL")}},TimedOutError:class extends n{constructor(){super(...arguments),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 l 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 d 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+)/,d],[/MSG_WAIT_(.*)/,u],[/PHONE_MIGRATE_(\d+)/,c],[/SLOWMODE_WAIT_(\d+)/,l],[/USER_MIGRATE_(\d+)/,r],[/NETWORK_MIGRATE_(\d+)/,f],[/EMAIL_UNCONFIRMED_(\d+)/,h]];e.exports={rpcErrorRe:m,FileMigrateError:p,FloodTestPhoneWaitError:g,FloodWaitError:d,PhoneMigrateError:c,SlowModeWaitError:l,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(663);e.exports=class extends s{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{types:void 0,func:void 0};super(),e.types?this.types=e.types:this.types=!0}build(e){return e}}},663:e=>{e.exports={EventBuilder:class{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{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(){let e;return e=arguments.length>0&&void 0!==arguments[0]&&!arguments[0]?this.stream.readUInt32LE(this.offset):this.stream.readInt32LE(this.offset),this.offset+=4,e}readLong(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this.readLargeInt(64,e)}readFloat(){return this.read(4).readFloatLE(0)}readDouble(){return this.read(8).readDoubleLE(0)}readLargeInt(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const n=this.read(Math.floor(e/8));return o(n,!0,t)}read(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-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){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];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),l=n(8960),d=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:l,errors:d,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}],l=new Map;c.forEach((e=>{let{fingerprint:t,...n}=e;l.set(t.toString(),n)}));var d=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),v=new(a().PQInnerData)({pq:h.getByteArray(r),p:y,q:b,nonce:o.nonce,serverNonce:o.serverNonce,newNonce:w}).getBytes();if(v.length>144)throw new i.SecurityError("Step 1 invalid nonce from server");let I,C;for(const e of o.serverPublicKeyFingerprints)if(C=l.get(e.toString()),void 0!==C){I=e;break}if(void 0===I||void 0===C)throw new i.SecurityError("Step 2 could not find a valid key for fingerprints");const A=h.generateRandomBytes(192-v.length),S=d.concat([v,A]),P=d.from(S).reverse();let M;for(let e=0;e<20;e++){const e=h.generateRandomBytes(32),n=await h.sha256(d.concat([e,S])),s=d.concat([P,n]),a=new g(e,d.alloc(32)).encryptIge(s),i=h.bufferXor(e,await h.sha256(a)),o=d.concat([i,a]),r=h.readBigIntFromBuffer(o,!1,!1);if(r.greaterOrEquals(C.n)){t.debug("Aes key greater than RSA. retrying");continue}const c=h.modExp(r,u(C.e),C.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),B=new m(D);B.read(20);const T=B.tgReadObject();if(!(T instanceof a().ServerDHInnerData))throw new Error(`Step 3 answer was ${T}`);if(T.nonce.neq(o.nonce))throw new i.SecurityError("Step 3 Invalid nonce in encrypted answer");if(T.serverNonce.neq(o.serverNonce))throw new i.SecurityError("Step 3 Invalid server nonce in encrypted answer");const x=h.readBigIntFromBuffer(T.dhPrime,!1,!1),V=h.readBigIntFromBuffer(T.gA,!1,!1),N=T.serverTime-Math.floor((new Date).getTime()/1e3),F=h.readBigIntFromBuffer(h.generateRandomBytes(256),!1,!1),L=h.modExp(u(T.g),F,x),q=h.modExp(V,F,x),O=new(a().ClientDHInnerData)({nonce:o.nonce,serverNonce:o.serverNonce,retryId:u.zero,gB:h.getByteArray(L,!1)}).getBytes(),H=d.concat([await h.sha1(O),O]),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(q));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),l=s.alloc(4);l.writeInt32LE(t.length,0);const d=s.concat([s.concat([s.alloc(8),i,l]),t]);if(await this._connection.send(d),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),l=n(2301),d=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(8744),{BadMessageError:v}=n(8187),{BadServerSalt:I,BadMsgNotification:C,MsgDetailedInfo:A,MsgNewDetailedInfo:S,NewSessionCreated:P,FutureSalts:M,MsgsStateReq:k,MsgResendReq:R,MsgsAllInfo:U}=n(7404).constructors,{SecurityError:E}=n(8187),{InvalidBufferError:D}=n(8187),{LogOut:B}=n(7404).requests.auth,{RPCMessageToError:T}=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.isReconnecting=!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={[l.CONSTRUCTOR_ID]:this._handleRPCResult.bind(this),[d.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),[C.CONSTRUCTOR_ID]:this._handleBadNotification.bind(this),[A.CONSTRUCTOR_ID]:this._handleDetailedInfo.bind(this),[S.CONSTRUCTOR_ID]:this._handleNewDetailedInfo.bind(this),[P.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.userDisconnected=!1,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.isReconnecting}`);const e=await this._send_queue.get();if(this.isReconnecting)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.isReconnecting;){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=T(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 v(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 B&&(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.isReconnecting&&(this.isReconnecting=!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.isReconnecting=!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:l}=n(2058),{SecurityError:d,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 l=s.alloc(4);l.writeInt32LE(o,0);const d=s.alloc(4);d.writeInt32LE(r.length,0);const u=p(i,8);return e.write(s.concat([u,l,d])),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:l}=await this._calcKey(this.authKey.getKey(),r,!0),d=i.readBufferFromBigInt(this.authKey.keyId,8);return s.concat([d,r,new o(l,c).encryptIge(s.concat([e,a]))])}async decryptMessageData(e){if(e.length<8)throw new u(e);if(e.length<0)throw new d("Server replied with negative length");if(e.length%4!=0)throw new d("Server replied with length not divisible by 4");if(i.readBigIntFromBuffer(e.slice(0,8)).neq(this.authKey.keyId))throw new d("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 d("Received msg_key doesn't match with expected one");const g=new r(e);if(g.readLong(),!g.readLong().eq(this.id))throw new d("Server replied with a wrong session ID");const p=g.readLong();if(this.msgIds.includes(p.toString()))throw new d("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 d("Server replied with the wrong message padding");const _=g.tgReadObject();return new l(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){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};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(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];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(){super(...arguments),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 l extends c{constructor(e){super(e),this.tag=l.tag,this.obfuscateTag=l.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(l,"tag",s.from("ef","hex")),a(l,"obfuscateTag",s.from("efefefef","hex")),e.exports={ConnectionTCPAbridged:class extends r{constructor(){super(...arguments),a(this,"PacketCodecClass",l)}},AbridgedPacketCodec:l}},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 l{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)),l=s.from(a.slice(0,32)),d=s.from(a.slice(32,48)),u=new c(o,r),g=new c(l,d);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(){super(...arguments),a(this,"ObfuscatedIO",l),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)=>{const s=n(5585),a=n(4046),{Connection:i,ConnectionTCPFull:o,ConnectionTCPAbridged:r,ConnectionTCPObfuscated:c}=n(417),{UpdateConnectionState:l,UpdateServerTimeOffset:d}=n(8744);e.exports={Connection:i,ConnectionTCPFull:o,ConnectionTCPAbridged:r,ConnectionTCPObfuscated:c,MTProtoPlainSender:s,MTProtoSender:a,UpdateConnectionState:l,UpdateServerTimeOffset:d}},8744: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){this.state=e,this.origin=t}}t(n,"disconnected",-1),t(n,"connected",1),t(n,"broken",0),e.exports={UpdateConnectionState:n,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){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];this._dcId=e,this._serverAddress=t,this._port=n,delete this._authKeys[e],s||this._onUpdate()}getAuthKey(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this._dcId;return this._authKeys[e]}setAuthKey(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]: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(4678),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){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];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(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this._dcId;return this._authKeys[e]}setAuthKey(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]: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(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:void 0;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:139,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),l=n(4779),d=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":case"bytes":return o(e);case"Bool":return e?s.from("b5757299","hex"):s.from("379779bc","hex");case"true":return s.alloc(0);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#a8edd0f5 flags:# pinned:flags.2?true unread_mark:flags.3?true peer:Peer top_message:int read_inbox_max_id:int read_outbox_max_id:int unread_count:int unread_mentions_count:int unread_reactions_count:int notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?int = Dialog;\ndialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog;\nphotoEmpty#2331b22d id:long = Photo;\nphoto#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector 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;\ninputReportReasonIllegalDrugs#a8eb2be = ReportReason;\ninputReportReasonPersonalDetails#9ec7863d = 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 videos:flags.6?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 rtmp_stream:flags.12?true listeners_hidden:flags.13?true id:long access_hash:long participants_count:int title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int unmuted_video_count:flags.10?int unmuted_video_limit:int version:int = GroupCall;\ninputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall;\ngroupCallParticipant#eba636fe flags:# muted:flags.0?true left:flags.1?true can_self_unmute:flags.2?true just_joined:flags.4?true versioned:flags.5?true min:flags.8?true muted_by_you:flags.9?true volume_by_admin:flags.10?true self:flags.12?true video_joined:flags.15?true peer:Peer date:int active_date:flags.3?int source:int volume:flags.7?int about:flags.11?string raise_hand_rating:flags.13?long video:flags.6?GroupCallParticipantVideo presentation:flags.14?GroupCallParticipantVideo = GroupCallParticipant;\nphone.groupCall#9e727aad call:GroupCall participants:Vector 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#4f2b9479 flags:# min:flags.0?true can_see_list:flags.2?true results:Vector recent_reactions:flags.1?Vector = MessageReactions;\nmessages.messageReactionsList#31bd492d flags:# count:int reactions:Vector chats:Vector users:Vector next_offset:flags.0?string = messages.MessageReactionsList;\navailableReaction#c077ec01 flags:# inactive:flags.0?true reaction:string title:string static_icon:Document appear_animation:Document select_animation:Document activate_animation:Document effect_animation:Document around_animation:flags.1?Document center_icon:flags.1?Document = AvailableReaction;\nmessages.availableReactionsNotModified#9f071957 = messages.AvailableReactions;\nmessages.availableReactions#768e3aad hash:int reactions:Vector = messages.AvailableReactions;\nmessages.translateNoResult#67ca4737 = messages.TranslatedText;\nmessages.translateResultText#a214f7d0 text:string = messages.TranslatedText;\nmessagePeerReaction#51b67eff flags:# big:flags.0?true unread:flags.1?true peer_id:Peer reaction:string = MessagePeerReaction;\ngroupCallStreamChannel#80eb48af channel:int scale:int last_timestamp_ms:long = GroupCallStreamChannel;\nphone.groupCallStreamChannels#d0e482b2 channels:Vector = phone.GroupCallStreamChannels;\nphone.groupCallStreamRtmpUrl#2dbf3432 url:string key:string = phone.GroupCallStreamRtmpUrl;\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;\ncontacts.resolvePhone#8af94344 phone:string = contacts.ResolvedPeer;\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.reportSpam#cf1592db peer:InputPeer = Bool;\nmessages.getPeerSettings#efd9a6a2 peer:InputPeer = messages.PeerSettings;\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.saveGif#327a30cb id:InputDocument unsave:Bool = Bool;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\nmessages.sendInlineBotResult#7aa11297 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true hide_via:flags.11?true peer:InputPeer reply_to_msg_id:flags.0?int random_id:long query_id:long id:string schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.editMessage#48f71778 flags:# no_webpage:flags.1?true peer:InputPeer id:int message:flags.11?string media:flags.14?InputMedia reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector 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.hidePeerSettingsBar#4facb138 peer:InputPeer = Bool;\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.getExportedChatInvites#a2b5a3f6 flags:# revoked:flags.3?true peer:InputPeer admin_id:InputUser offset_date:flags.2?int offset_link:flags.2?string limit:int = messages.ExportedChatInvites;\nmessages.editExportedChatInvite#bdca2f75 flags:# revoked:flags.2?true peer:InputPeer link:string expire_date:flags.0?int usage_limit:flags.1?int request_needed:flags.3?Bool title:flags.4?string = messages.ExportedChatInvite;\nmessages.deleteRevokedExportedChatInvites#56987bd5 peer:InputPeer admin_id:InputUser = Bool;\nmessages.deleteExportedChatInvite#d464a42b peer:InputPeer link:string = Bool;\nmessages.getChatInviteImporters#df04dd4e flags:# requested:flags.0?true peer:InputPeer link:flags.1?string q:flags.2?string offset_date:int offset_user:InputUser limit:int = messages.ChatInviteImporters;\nmessages.getMessageReadParticipants#2c6f97b7 peer:InputPeer msg_id:int = Vector;\nmessages.hideChatJoinRequest#7fe7e815 flags:# approved:flags.0?true peer:InputPeer user_id:InputUser = Updates;\nmessages.hideAllChatJoinRequests#e085f4ea flags:# approved:flags.0?true peer:InputPeer link:flags.1?string = Updates;\nmessages.toggleNoForwards#b11eafa2 peer:InputPeer enabled:Bool = Updates;\nmessages.saveDefaultSendAs#ccfddf96 peer:InputPeer send_as:InputPeer = Bool;\nmessages.sendReaction#25690ce4 flags:# big:flags.1?true peer:InputPeer msg_id:int reaction:flags.0?string = Updates;\nmessages.getMessagesReactions#8bba90e6 peer:InputPeer id:Vector = Updates;\nmessages.getMessageReactionsList#e0ee6b77 flags:# peer:InputPeer id:int reaction:flags.0?string offset:flags.1?string limit:int = messages.MessageReactionsList;\nmessages.setChatAvailableReactions#14050ea6 peer:InputPeer available_reactions:Vector = Updates;\nmessages.getAvailableReactions#18dea0ac hash:int = messages.AvailableReactions;\nmessages.setDefaultReaction#d960c4d4 reaction:string = 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.getAppConfig#98914110 = JSONValue;\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:# rtmp_stream:flags.2?true peer:InputPeer random_id:int title:flags.0?string schedule_date:flags.1?int = Updates;\nphone.joinGroupCall#b132ff7b flags:# muted:flags.0?true video_stopped:flags.2?true call:InputGroupCall join_as:InputPeer invite_hash:flags.1?string params:DataJSON = Updates;\nphone.leaveGroupCall#500377f9 call:InputGroupCall source:int = Updates;\nphone.discardGroupCall#7a777135 call:InputGroupCall = Updates;\nphone.getGroupCall#41845db call:InputGroupCall limit:int = phone.GroupCall;\nphone.getGroupParticipants#c558d8ab call:InputGroupCall ids:Vector 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;\nstats.getBroadcastStats#ab42441a flags:# dark:flags.0?true channel:InputChannel = stats.BroadcastStats;\nstats.loadAsyncGraph#621d5fa0 flags:# token:string x:flags.0?long = StatsGraph;\nstats.getMegagroupStats#dcdf8607 flags:# dark:flags.0?true channel:InputChannel = stats.MegagroupStats;"},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 l(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 d=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];e.flags.includes("g")||(e=new RegExp(e.source,"g"));const s=e.exec(t);return s&&(n.push(s.slice(1)),d(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=d(/({)?(\w+):([\w\d<>#.?!]+)}?/,e),r={name:n[1],constructorId:parseInt(n[2],16),argsConfig:{},subclassOfId:l(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=l(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:d,parseTl:function*(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:o;(n||[]).reduce(((e,t)=>({...e,[t.name]:t})),{});const a=[],i={},c={},l=e;let d=!1;for(let e of l.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;d="functions"===e}else try{const t=u(e,d);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,[802,313],(()=>a(1742)));return a.O(e)},e=[],a.O=(t,n,s,i)=>{if(!n){var o=1/0;for(d=0;d=i)&&Object.keys(a.O).every((e=>a.O[e](n[c])))?n.splice(c--,1):(r=!1,i0&&e[d-1][2]>i;d--)e[d]=e[d-1];e[d]=[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+"."+{313:"5cd1718104a79212da23",802:"acd83f1b28a8893b9dba"}[e]+".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={742: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=()=>Promise.all([a.e(802),a.e(313)]).then(t),a.x()})(); +//# sourceMappingURL=742.b2feed9283c594eb9e2f.js.map \ No newline at end of file diff --git a/dist/742.e09d8d2bec0ce4cf0543.js.map b/dist/742.b2feed9283c594eb9e2f.js.map similarity index 99% rename from dist/742.e09d8d2bec0ce4cf0543.js.map rename to dist/742.b2feed9283c594eb9e2f.js.map index 389eb01b..4fe928c3 100644 --- a/dist/742.e09d8d2bec0ce4cf0543.js.map +++ b/dist/742.b2feed9283c594eb9e2f.js.map @@ -1 +1 @@ -{"version":3,"file":"742.e09d8d2bec0ce4cf0543.js","mappings":"UAAIA,ECAAC,E,6xJCAG,MA+GMC,GArEyB,oBAAXC,QAA0BA,OAAOC,YAqEzBC,KAAKC,MAAM,MACjCC,EAA6B,IAAIC,IAAI,CAChD,aAAc,sBAAuB,iBAAkB,0BAA2B,kBA6BvEC,EAAgC,IAAID,IAAI,CACnD,YAAa,YAAa,eAGfE,EAAgC,IAAIF,IAAI,CACnD,cAoBWG,GAjB6B,IAAIH,IAAI,IAC7CC,KACAC,IAYyC,IAAIF,IAAI,CAAC,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,OAGhH,UC1C7C,IA4BII,EACAC,E,cChJG,SAASC,EAA2CC,EAAiBC,GA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lC,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/payments.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/payments.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/appConfig.ts","webpack://telegram-t/./src/api/gramjs/methods/settings.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/bots.ts","webpack://telegram-t/./src/api/gramjs/methods/bots.ts","webpack://telegram-t/./src/api/gramjs/methods/reactions.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/statistics.ts","webpack://telegram-t/./src/api/gramjs/methods/statistics.ts","webpack://telegram-t/./src/api/gramjs/provider.ts","webpack://telegram-t/./src/api/gramjs/worker/worker.ts","webpack://telegram-t/./src/lib/gramjs/Helpers.js","webpack://telegram-t/./src/lib/gramjs/Password.js","webpack://telegram-t/./src/lib/gramjs/Utils.js","webpack://telegram-t/./src/lib/gramjs/Version.js","webpack://telegram-t/./src/lib/gramjs/client/2fa.ts","webpack://telegram-t/./src/lib/gramjs/client/TelegramClient.js","webpack://telegram-t/./src/lib/gramjs/client/auth.ts","webpack://telegram-t/./src/lib/gramjs/client/downloadFile.ts","webpack://telegram-t/./src/lib/gramjs/client/uploadFile.ts","webpack://telegram-t/./src/lib/gramjs/crypto/AuthKey.js","webpack://telegram-t/./src/lib/gramjs/crypto/CTR.js","webpack://telegram-t/./src/lib/gramjs/crypto/Factorizator.js","webpack://telegram-t/./src/lib/gramjs/crypto/IGE.js","webpack://telegram-t/./src/lib/gramjs/crypto/converters.ts","webpack://telegram-t/./src/lib/gramjs/crypto/crypto.js","webpack://telegram-t/./src/lib/gramjs/crypto/words.ts","webpack://telegram-t/./src/lib/gramjs/errors/Common.js","webpack://telegram-t/./src/lib/gramjs/errors/RPCBaseErrors.js","webpack://telegram-t/./src/lib/gramjs/errors/RPCErrorList.js","webpack://telegram-t/./src/lib/gramjs/errors/index.js","webpack://telegram-t/./src/lib/gramjs/events/Raw.js","webpack://telegram-t/./src/lib/gramjs/events/common.js","webpack://telegram-t/./src/lib/gramjs/events/index.js","webpack://telegram-t/./src/lib/gramjs/extensions/AsyncQueue.js","webpack://telegram-t/./src/lib/gramjs/extensions/BinaryReader.js","webpack://telegram-t/./src/lib/gramjs/extensions/BinaryWriter.js","webpack://telegram-t/./src/lib/gramjs/extensions/Logger.js","webpack://telegram-t/./src/lib/gramjs/extensions/MessagePacker.js","webpack://telegram-t/./src/lib/gramjs/extensions/PromisedWebSockets.js","webpack://telegram-t/./src/lib/gramjs/extensions/index.js","webpack://telegram-t/./src/lib/gramjs/index.js","webpack://telegram-t/./src/lib/gramjs/crypto/RSA.ts","webpack://telegram-t/./src/lib/gramjs/network/Authenticator.ts","webpack://telegram-t/./src/lib/gramjs/network/MTProtoPlainSender.js","webpack://telegram-t/./src/lib/gramjs/network/MTProtoSender.js","webpack://telegram-t/./src/lib/gramjs/network/MTProtoState.js","webpack://telegram-t/./src/lib/gramjs/network/RequestState.js","webpack://telegram-t/./src/lib/gramjs/network/connection/Connection.js","webpack://telegram-t/./src/lib/gramjs/network/connection/TCPAbridged.js","webpack://telegram-t/./src/lib/gramjs/network/connection/TCPObfuscated.js","webpack://telegram-t/./src/lib/gramjs/network/connection/index.js","webpack://telegram-t/./src/lib/gramjs/network/index.js","webpack://telegram-t/./src/lib/gramjs/network/updates.js","webpack://telegram-t/./src/lib/gramjs/sessions/Abstract.js","webpack://telegram-t/./src/lib/gramjs/sessions/CacheApiSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/CallbackSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/IdbSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/LocalStorageSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/Memory.js","webpack://telegram-t/./src/lib/gramjs/sessions/StorageSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/StringSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/index.js","webpack://telegram-t/./src/lib/gramjs/tl/AllTLObjects.js","webpack://telegram-t/./src/lib/gramjs/tl/api.js","webpack://telegram-t/./src/lib/gramjs/tl/apiTl.js","webpack://telegram-t/./src/lib/gramjs/tl/core/GZIPPacked.js","webpack://telegram-t/./src/lib/gramjs/tl/core/MessageContainer.js","webpack://telegram-t/./src/lib/gramjs/tl/core/RPCResult.js","webpack://telegram-t/./src/lib/gramjs/tl/core/TLMessage.js","webpack://telegram-t/./src/lib/gramjs/tl/core/index.js","webpack://telegram-t/./src/lib/gramjs/tl/generationHelpers.js","webpack://telegram-t/./src/lib/gramjs/tl/index.js","webpack://telegram-t/./src/lib/gramjs/tl/schemaTl.js","webpack://telegram-t/webpack/bootstrap","webpack://telegram-t/webpack/runtime/compat get default export","webpack://telegram-t/webpack/runtime/define property getters","webpack://telegram-t/webpack/runtime/ensure chunk","webpack://telegram-t/webpack/runtime/get javascript chunk filename","webpack://telegram-t/webpack/runtime/get mini-css chunk filename","webpack://telegram-t/webpack/runtime/global","webpack://telegram-t/webpack/runtime/hasOwnProperty shorthand","webpack://telegram-t/webpack/runtime/make namespace object","webpack://telegram-t/webpack/runtime/node module decorator","webpack://telegram-t/webpack/runtime/publicPath","webpack://telegram-t/webpack/runtime/importScripts chunk loading","webpack://telegram-t/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var next = __webpack_require__.x;\n__webpack_require__.x = () => {\n\treturn Promise.all([\n\t\t__webpack_require__.e(802),\n\t\t__webpack_require__.e(313)\n\t]).then(next);\n};","export const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION!;\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 PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const DEBUG_PAYMENT_SMART_GLOCAL = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 500;\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 200;\nexport const GLOBAL_STATE_CACHE_CHATS_WITH_MESSAGES_LIMIT = 30;\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-v8';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const AUTODOWNLOAD_FILESIZE_MB_LIMITS = [1, 5, 10, 50, 100, 500];\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\nexport const GROUP_CALL_PARTICIPANTS_LIMIT = 100;\nexport const REACTION_LIST_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\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\nexport const CUSTOM_APPENDIX_ATTRIBUTE = 'data-has-custom-appendix';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const 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 = 100;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const STICKER_SIZE_JOIN_REQUESTS = 140;\nexport const STICKER_SIZE_INVITES = 140;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const NO_STICKER_SET_ID = 'NO_STICKER_SET';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\nexport const VIDEO_WEBM_TYPE = 'video/webm';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const 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\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: T[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(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 | GramJs.DocumentAttributeVideo,\n): ApiThumbnail | undefined {\n const { w, h } = sizeAttribute;\n const dataUri = `data:image/svg+xml;utf8,${pathBytesToSvg(photoSize.bytes, w, h)}`;\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiPhoto(photo: GramJs.Photo): ApiPhoto {\n const sizes = photo.sizes\n .filter((s: any): s is GramJs.PhotoSize => {\n return s instanceof GramJs.PhotoSize || s instanceof GramJs.PhotoSizeProgressive;\n })\n .map(buildApiPhotoSize);\n\n return {\n id: String(photo.id),\n thumbnail: buildApiThumbnailFromStripped(photo.sizes),\n sizes,\n };\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 {\n ApiEmojiInteraction, ApiSticker, ApiStickerSet, GramJsEmojiInteraction,\n} from '../../types';\nimport { NO_STICKER_SET_ID } from '../../../config';\n\nimport { buildApiThumbnailFromCached, buildApiThumbnailFromPath } from './common';\nimport localDb from '../localDb';\n\nconst LOTTIE_STICKER_MIME_TYPE = 'application/x-tgsticker';\nconst VIDEO_STICKER_MIME_TYPE = 'video/webm';\n\nexport function buildStickerFromDocument(document: GramJs.TypeDocument): ApiSticker | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const { mimeType } = document;\n const stickerAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeSticker => (\n attr instanceof GramJs.DocumentAttributeSticker\n ));\n\n const fileAttribute = (mimeType === LOTTIE_STICKER_MIME_TYPE || mimeType === VIDEO_STICKER_MIME_TYPE)\n && document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeFilename => (\n attr instanceof GramJs.DocumentAttributeFilename\n ));\n\n if (!stickerAttribute && !fileAttribute) {\n return undefined;\n }\n\n const isLottie = mimeType === LOTTIE_STICKER_MIME_TYPE;\n const isVideo = mimeType === VIDEO_STICKER_MIME_TYPE;\n\n const imageSizeAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeImageSize => (\n attr instanceof GramJs.DocumentAttributeImageSize\n ));\n\n const videoSizeAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeVideo => (\n attr instanceof GramJs.DocumentAttributeVideo\n ));\n\n const sizeAttribute = imageSizeAttribute || videoSizeAttribute;\n\n const stickerSetInfo = stickerAttribute && stickerAttribute.stickerset instanceof GramJs.InputStickerSetID\n ? stickerAttribute.stickerset\n : undefined;\n const emoji = stickerAttribute?.alt;\n\n const cachedThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoCachedSize => s instanceof GramJs.PhotoCachedSize,\n );\n\n // eslint-disable-next-line no-restricted-globals\n if (mimeType === VIDEO_STICKER_MIME_TYPE && !(self as any).isWebmSupported && !cachedThumb) {\n const staticThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize,\n );\n\n if (!staticThumb) {\n return undefined;\n }\n }\n\n const pathThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoPathSize => s instanceof GramJs.PhotoPathSize,\n );\n\n const thumbnail = cachedThumb ? (\n buildApiThumbnailFromCached(cachedThumb)\n ) : pathThumb && sizeAttribute ? (\n buildApiThumbnailFromPath(pathThumb, sizeAttribute)\n ) : undefined;\n\n const { w: width, h: height } = cachedThumb as GramJs.PhotoCachedSize || sizeAttribute || {};\n\n return {\n id: String(document.id),\n stickerSetId: stickerSetInfo ? String(stickerSetInfo.id) : NO_STICKER_SET_ID,\n stickerSetAccessHash: stickerSetInfo && String(stickerSetInfo.accessHash),\n emoji,\n isLottie,\n isVideo,\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 videos,\n id,\n accessHash,\n title,\n thumbs,\n count,\n shortName,\n } = set;\n\n return {\n archived,\n isLottie: animated,\n isVideos: videos,\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\nexport function buildApiEmojiInteraction(json: GramJsEmojiInteraction): ApiEmojiInteraction {\n return {\n timestamps: json.a.map((l) => l.t),\n };\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 isLottie: boolean;\n isVideo: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isLottie?: true;\n isVideos?: 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\ninterface ApiGeoPoint {\n long: number;\n lat: number;\n accessHash: string;\n accuracyRadius?: number;\n}\n\ninterface ApiGeo {\n type: 'geo';\n geo: ApiGeoPoint;\n}\n\ninterface ApiVenue {\n type: 'venue';\n geo: ApiGeoPoint;\n title: string;\n address: string;\n provider: string;\n venueId: string;\n venueType: string;\n}\n\ninterface ApiGeoLive {\n type: 'geoLive';\n geo: ApiGeoPoint;\n heading?: number;\n period: number;\n}\n\nexport type ApiLocation = ApiGeo | ApiVenue | ApiGeoLive;\n\nexport type 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 Spoiler = 'MessageEntitySpoiler',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: string;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n location?: ApiLocation;\n };\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 reactors?: {\n nextOffset?: string;\n count: number;\n reactions: ApiUserReaction[];\n };\n reactions?: ApiReactions;\n}\n\nexport interface ApiReactions {\n canSeeList?: boolean;\n results: ApiReactionCount[];\n recentReactions?: ApiUserReaction[];\n}\n\nexport interface ApiUserReaction {\n userId: string;\n reaction: string;\n}\n\nexport interface ApiReactionCount {\n isChosen?: boolean;\n count: number;\n reaction: string;\n}\n\nexport interface ApiAvailableReaction {\n selectAnimation?: ApiDocument;\n staticIcon?: ApiDocument;\n centerIcon?: ApiDocument;\n aroundAnimation?: ApiDocument;\n reaction: string;\n title: string;\n isInactive?: 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' | 'illegalDrugs' | 'personalDetails' | '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 | ArrayBuffer;\nexport type ApiPreparedMedia = 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 case ApiMessageEntityTypes.Spoiler:\n return new GramJs.MessageEntitySpoiler({ offset, length });\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 'illegalDrugs':\n return new GramJs.InputReportReasonIllegalDrugs();\n case 'personalDetails':\n return new GramJs.InputReportReasonPersonalDetails();\n case 'other':\n return new GramJs.InputReportReasonOther();\n }\n\n return undefined;\n}\n\nexport function buildSendMessageAction(action: ApiSendMessageAction) {\n switch (action.type) {\n case 'cancel':\n return new GramJs.SendMessageCancelAction();\n case 'typing':\n return new GramJs.SendMessageTypingAction();\n case 'recordAudio':\n return new GramJs.SendMessageRecordAudioAction();\n case 'chooseSticker':\n return new GramJs.SendMessageChooseStickerAction();\n }\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 ApiReactions,\n ApiReactionCount,\n ApiUserReaction,\n ApiAvailableReaction,\n ApiSponsoredMessage,\n ApiUser,\n ApiLocation,\n} from '../../types';\n\nimport {\n DELETED_COMMENTS_CHANNEL_ID,\n LOCAL_MESSAGE_ID_BASE,\n SERVICE_NOTIFICATIONS_USER_ID,\n SPONSORED_MESSAGE_CACHE_MS,\n SUPPORTED_IMAGE_CONTENT_TYPES,\n SUPPORTED_VIDEO_CONTENT_TYPES,\n VIDEO_MOV_TYPE,\n VIDEO_WEBM_TYPE,\n} from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { buildStickerFromDocument } from './symbols';\nimport { buildApiPhoto, buildApiPhotoSize, buildApiThumbnailFromStripped } from './common';\nimport { interpolateArray } from '../../../util/waveform';\nimport { buildPeer } from '../gramjsBuilders';\nimport { addPhotoToLocalDb, resolveMessageApiChatId, serializeBytes } from '../helpers';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer, isPeerUser } from './peers';\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 const content = buildMessageContent(notification);\n\n return {\n id: localId,\n chatId: SERVICE_NOTIFICATIONS_USER_ID,\n date: notification.inboxDate || currentDate,\n content,\n isOutgoing: false,\n };\n}\n\ntype UniversalMessage = (\n Pick\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' | 'reactions'\n )>\n);\n\nexport function buildApiMessageWithChatId(chatId: string, mtpMessage: UniversalMessage): ApiMessage {\n const fromId = mtpMessage.fromId ? getApiChatIdFromMtpPeer(mtpMessage.fromId) : undefined;\n const peerId = mtpMessage.peerId ? getApiChatIdFromMtpPeer(mtpMessage.peerId) : undefined;\n const isChatWithSelf = !fromId && chatId === currentUserId;\n const isOutgoing = (mtpMessage.out && !mtpMessage.post) || (isChatWithSelf && !mtpMessage.fwdFrom);\n const content = buildMessageContent(mtpMessage);\n const action = mtpMessage.action\n && buildAction(mtpMessage.action, fromId, peerId, Boolean(mtpMessage.post), isOutgoing);\n if (action) {\n content.action = action;\n }\n\n const { replyToMsgId, replyToTopId, replyToPeerId } = mtpMessage.replyTo || {};\n const isEdited = mtpMessage.editDate && !mtpMessage.editHide;\n const {\n inlineButtons, keyboardButtons, keyboardPlaceholder, isKeyboardSingleUse,\n } = buildReplyButtons(mtpMessage) || {};\n const forwardInfo = mtpMessage.fwdFrom && buildApiMessageForwardInfo(mtpMessage.fwdFrom, isChatWithSelf);\n const { replies, mediaUnread: isMediaUnread, postAuthor } = mtpMessage;\n const groupedId = mtpMessage.groupedId && String(mtpMessage.groupedId);\n const isInAlbum = Boolean(groupedId) && !(content.document || content.audio || content.sticker);\n const shouldHideKeyboardButtons = mtpMessage.replyMarkup instanceof GramJs.ReplyKeyboardHide;\n\n return {\n id: mtpMessage.id,\n chatId,\n isOutgoing,\n content,\n date: mtpMessage.date,\n senderId: fromId || (mtpMessage.out && mtpMessage.post && currentUserId) || chatId,\n views: mtpMessage.views,\n isFromScheduled: mtpMessage.fromScheduled,\n reactions: mtpMessage.reactions && buildMessageReactions(mtpMessage.reactions),\n ...(replyToMsgId && { replyToMessageId: replyToMsgId }),\n ...(replyToPeerId && { replyToChatId: getApiChatIdFromMtpPeer(replyToPeerId) }),\n ...(replyToTopId && { replyToTopMessageId: replyToTopId }),\n ...(forwardInfo && { forwardInfo }),\n ...(isEdited && { isEdited }),\n ...(mtpMessage.editDate && { editDate: mtpMessage.editDate }),\n ...(isMediaUnread && { isMediaUnread }),\n ...(mtpMessage.mentioned && isMediaUnread && { hasUnreadMention: true }),\n ...(mtpMessage.mentioned && { isMentioned: true }),\n ...(groupedId && {\n groupedId,\n isInAlbum,\n }),\n inlineButtons,\n ...(keyboardButtons && { keyboardButtons, keyboardPlaceholder, isKeyboardSingleUse }),\n ...(shouldHideKeyboardButtons && { shouldHideKeyboardButtons }),\n ...(mtpMessage.viaBotId && { viaBotId: buildApiPeerId(mtpMessage.viaBotId, 'user') }),\n ...(replies?.comments && { threadInfo: buildThreadInfo(replies, mtpMessage.id, chatId) }),\n ...(postAuthor && { adminTitle: postAuthor }),\n ...(mtpMessage.noforwards && { isProtected: true }),\n };\n}\n\nexport function buildMessageReactions(reactions: GramJs.MessageReactions): ApiReactions {\n const {\n recentReactions, results, canSeeList,\n } = reactions;\n\n return {\n canSeeList,\n results: results.map(buildReactionCount),\n recentReactions: recentReactions?.map(buildMessagePeerReaction),\n };\n}\n\nfunction buildReactionCount(reactionCount: GramJs.ReactionCount): ApiReactionCount {\n const { chosen, count, reaction } = reactionCount;\n\n return {\n isChosen: chosen,\n count,\n reaction,\n };\n}\n\nexport function buildMessagePeerReaction(userReaction: GramJs.MessagePeerReaction): ApiUserReaction {\n const { peerId, reaction } = userReaction;\n\n return {\n userId: getApiChatIdFromMtpPeer(peerId),\n reaction,\n };\n}\n\nexport function buildApiAvailableReaction(availableReaction: GramJs.AvailableReaction): ApiAvailableReaction {\n const {\n selectAnimation, staticIcon, reaction, title,\n inactive, aroundAnimation, centerIcon,\n } = availableReaction;\n\n return {\n selectAnimation: buildApiDocument(selectAnimation),\n staticIcon: buildApiDocument(staticIcon),\n aroundAnimation: aroundAnimation ? buildApiDocument(aroundAnimation) : undefined,\n centerIcon: centerIcon ? buildApiDocument(centerIcon) : undefined,\n reaction,\n title,\n isInactive: inactive,\n };\n}\n\nexport function buildMessageContent(\n mtpMessage: UniversalMessage | GramJs.UpdateServiceNotification,\n) {\n let content: ApiMessage['content'] = {};\n\n if (mtpMessage.media) {\n content = {\n ...buildMessageMediaContent(mtpMessage.media),\n };\n }\n\n if (mtpMessage.message && !content.sticker && !content.poll && !content.contact && !(content.video?.isRound)) {\n content = {\n ...content,\n text: buildMessageTextContent(mtpMessage.message, mtpMessage.entities),\n };\n }\n\n return content;\n}\n\nexport function buildMessageTextContent(\n message: string,\n entities?: GramJs.TypeMessageEntity[],\n): ApiFormattedText {\n return {\n text: message,\n ...(entities && { entities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildMessageDraft(draft: GramJs.TypeDraftMessage) {\n if (draft instanceof GramJs.DraftMessageEmpty) {\n return undefined;\n }\n\n const {\n message, entities, replyToMsgId, date,\n } = draft;\n\n return {\n formattedText: message ? buildMessageTextContent(message, entities) : undefined,\n replyingToId: replyToMsgId,\n date,\n };\n}\n\nexport function buildMessageMediaContent(media: GramJs.TypeMessageMedia): ApiMessage['content'] | undefined {\n if ('ttlSeconds' in media && media.ttlSeconds) {\n return undefined;\n }\n\n const sticker = buildSticker(media);\n if (sticker) return { sticker };\n\n const photo = buildPhoto(media);\n if (photo) return { photo };\n\n const video = buildVideo(media);\n if (video) return { video };\n\n const audio = buildAudio(media);\n if (audio) return { audio };\n\n const voice = buildVoice(media);\n if (voice) return { voice };\n\n const document = buildDocumentFromMedia(media);\n if (document) return { document };\n\n const contact = buildContact(media);\n if (contact) return { contact };\n\n const poll = buildPollFromMedia(media);\n if (poll) return { poll };\n\n const webPage = buildWebPage(media);\n if (webPage) return { webPage };\n\n const invoice = buildInvoiceFromMedia(media);\n if (invoice) return { invoice };\n\n const location = buildLocationFromMedia(media);\n if (location) return { location };\n\n 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_WEBM_TYPE && !(self as any).isWebmSupported) {\n return undefined;\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (mimeType === VIDEO_MOV_TYPE && !(self as any).isMovSupported) {\n return undefined;\n }\n\n const videoAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeVideo => a instanceof GramJs.DocumentAttributeVideo);\n\n if (!videoAttr) {\n return undefined;\n }\n\n const gifAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeAnimated => a instanceof GramJs.DocumentAttributeAnimated);\n\n const {\n duration,\n w: width,\n h: height,\n supportsStreaming = false,\n roundMessage: isRound = false,\n } = videoAttr;\n\n return {\n id: String(id),\n mimeType,\n duration,\n fileName: getFilenameFromDocument(document, 'video'),\n width,\n height,\n supportsStreaming,\n isRound,\n isGif: Boolean(gifAttr),\n thumbnail: buildApiThumbnailFromStripped(thumbs),\n size,\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\nfunction buildLocationFromMedia(media: GramJs.TypeMessageMedia): ApiLocation | undefined {\n if (media instanceof GramJs.MessageMediaGeo) {\n return buildGeo(media);\n }\n\n if (media instanceof GramJs.MessageMediaVenue) {\n return buildVenue(media);\n }\n\n if (media instanceof GramJs.MessageMediaGeoLive) {\n return buildGeoLive(media);\n }\n\n return undefined;\n}\n\nfunction buildGeo(media: GramJs.MessageMediaGeo): ApiLocation | undefined {\n const point = buildGeoPoint(media.geo);\n return point && { type: 'geo', geo: point };\n}\n\nfunction buildVenue(media: GramJs.MessageMediaVenue): ApiLocation | undefined {\n const {\n geo, title, provider, address, venueId, venueType,\n } = media;\n const point = buildGeoPoint(geo);\n return point && {\n type: 'venue',\n geo: point,\n title,\n provider,\n address,\n venueId,\n venueType,\n };\n}\n\nfunction buildGeoLive(media: GramJs.MessageMediaGeoLive): ApiLocation | undefined {\n const { geo, period, heading } = media;\n const point = buildGeoPoint(geo);\n return point && {\n type: 'geoLive',\n geo: point,\n period,\n heading,\n };\n}\n\nfunction buildGeoPoint(geo: GramJs.TypeGeoPoint): ApiLocation['geo'] | undefined {\n if (geo instanceof GramJs.GeoPointEmpty) return undefined;\n const {\n long, lat, accuracyRadius, accessHash,\n } = geo;\n return {\n long,\n lat,\n accessHash: accessHash.toString(),\n accuracyRadius,\n };\n}\n\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 ApiExportedInvite,\n ApiChatInviteImporter,\n ApiChatSettings,\n} from '../../types';\nimport { pick, pickTruthy } from '../../../util/iteratees';\nimport {\n buildApiPeerId, getApiChatIdFromMtpPeer, isPeerChat, isPeerUser,\n} from './peers';\nimport { omitVirtualClassFields } from './helpers';\nimport { getServerTime } from '../../../util/serverTime';\n\ntype PeerEntityApiChatFields = Omit;\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 let emoticon: string | undefined;\n if (update.action instanceof GramJs.SendMessageCancelAction) {\n return undefined;\n } else if (update.action instanceof GramJs.SendMessageTypingAction) {\n action = 'lng_user_typing';\n } else if (update.action instanceof GramJs.SendMessageRecordVideoAction) {\n action = 'lng_send_action_record_video';\n } else if (update.action instanceof GramJs.SendMessageUploadVideoAction) {\n action = 'lng_send_action_upload_video';\n } else if (update.action instanceof GramJs.SendMessageRecordAudioAction) {\n action = 'lng_send_action_record_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadAudioAction) {\n action = 'lng_send_action_upload_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadPhotoAction) {\n action = 'lng_send_action_upload_photo';\n } else if (update.action instanceof GramJs.SendMessageUploadDocumentAction) {\n action = 'lng_send_action_upload_file';\n } else if (update.action instanceof GramJs.SendMessageGeoLocationAction) {\n action = 'selecting a location to share';\n } else if (update.action instanceof GramJs.SendMessageChooseContactAction) {\n action = 'selecting a contact to share';\n } else if (update.action instanceof GramJs.SendMessageGamePlayAction) {\n action = 'lng_playing_game';\n } else if (update.action instanceof GramJs.SendMessageRecordRoundAction) {\n action = 'lng_send_action_record_round';\n } else if (update.action instanceof GramJs.SendMessageUploadRoundAction) {\n action = 'lng_send_action_upload_round';\n } else if (update.action instanceof GramJs.SendMessageChooseStickerAction) {\n action = 'lng_send_action_choose_sticker';\n } else if (update.action instanceof GramJs.SpeakingInGroupCallAction) {\n return undefined;\n } else if (update.action instanceof GramJs.SendMessageEmojiInteractionSeen) {\n action = 'lng_user_action_watching_animations';\n emoticon = update.action.emoticon;\n } else if (update.action instanceof GramJs.SendMessageEmojiInteraction) {\n return undefined;\n }\n\n return {\n action,\n ...(emoticon && { emoji: emoticon }),\n ...(!(update instanceof GramJs.UpdateUserTyping) && { userId: getApiChatIdFromMtpPeer(update.fromId) }),\n timestamp: Date.now() + serverTimeOffset * 1000,\n };\n}\n\nexport function buildApiChatFolder(filter: GramJs.DialogFilter): ApiChatFolder {\n return {\n ...pickTruthy(filter, [\n 'id', 'title', 'emoticon', 'contacts', 'nonContacts', 'groups', 'bots',\n 'excludeMuted', 'excludeRead', 'excludeArchived',\n ]),\n channels: filter.broadcasts,\n pinnedChatIds: filter.pinnedPeers.map(getApiChatIdFromMtpPeer).filter(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\nexport function buildApiExportedInvite(invite: GramJs.ChatInviteExported): ApiExportedInvite {\n const {\n revoked,\n date,\n expireDate,\n link,\n permanent,\n startDate,\n usage,\n usageLimit,\n requested,\n requestNeeded,\n title,\n adminId,\n } = invite;\n return {\n isRevoked: revoked,\n date,\n expireDate,\n link,\n isPermanent: permanent,\n startDate,\n usage,\n usageLimit,\n isRequestNeeded: requestNeeded,\n requested,\n title,\n adminId: buildApiPeerId(adminId, 'user'),\n };\n}\n\nexport function buildChatInviteImporter(importer: GramJs.ChatInviteImporter): ApiChatInviteImporter {\n const {\n userId,\n date,\n about,\n requested,\n } = importer;\n return {\n userId: buildApiPeerId(userId, 'user'),\n date,\n about,\n isRequested: requested,\n };\n}\n\nexport function buildApiChatSettings({\n autoarchived,\n reportSpam,\n addContact,\n blockContact,\n}: GramJs.PeerSettings): ApiChatSettings {\n return {\n isAutoArchived: Boolean(autoarchived),\n canReportSpam: Boolean(reportSpam),\n canAddContact: Boolean(addContact),\n canBlockContact: Boolean(blockContact),\n };\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\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 {\n ApiCountry, ApiSession, ApiWallpaper,\n} 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\nexport function buildJson(json: GramJs.TypeJSONValue): any {\n if (json instanceof GramJs.JsonNull) return undefined;\n if (json instanceof GramJs.JsonString\n || json instanceof GramJs.JsonBool\n || json instanceof GramJs.JsonNumber) return json.value;\n if (json instanceof GramJs.JsonArray) return json.value.map(buildJson);\n\n return json.value.reduce((acc: Record, el) => {\n acc[el.key] = buildJson(el.value);\n return acc;\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 buildMessageReactions,\n} from './apiBuilders/messages';\nimport {\n buildChatMember,\n buildChatMembers,\n buildChatTypingStatus,\n buildAvatarHash,\n buildApiChatFromPreview,\n buildApiChatFolder,\n buildApiChatSettings,\n} from './apiBuilders/chats';\nimport { buildApiUser, buildApiUserStatus } from './apiBuilders/users';\nimport {\n buildMessageFromUpdate,\n isMessageWithMedia,\n buildChatPhotoForLocalDb,\n} from './gramjsBuilders';\nimport localDb from './localDb';\nimport { omitVirtualClassFields } from './apiBuilders/helpers';\nimport { DEBUG } from '../../config';\nimport {\n addMessageToLocalDb,\n addEntitiesWithPhotosToLocalDb,\n addPhotoToLocalDb,\n resolveMessageApiChatId,\n serializeBytes,\n} from './helpers';\nimport { buildApiNotifyException, buildPrivacyKey, buildPrivacyRules } from './apiBuilders/misc';\nimport { buildApiPhoto } from './apiBuilders/common';\nimport {\n buildApiGroupCall,\n buildApiGroupCallParticipant,\n getGroupCallId,\n} from './apiBuilders/calls';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './apiBuilders/peers';\nimport { buildApiEmojiInteraction } from './apiBuilders/symbols';\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.MessageActionPaymentSent) {\n onUpdate({\n '@type': 'updatePaymentStateCompleted',\n });\n } else if (action instanceof GramJs.MessageActionChatEditTitle) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n title: action.title,\n },\n });\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n const photo = buildChatPhotoForLocalDb(action.photo);\n const avatarHash = buildAvatarHash(photo);\n\n const localDbChatId = resolveMessageApiChatId(update.message)!;\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = photo;\n }\n addPhotoToLocalDb(action.photo);\n\n if (avatarHash) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n avatarHash,\n },\n ...(action.photo instanceof GramJs.Photo && { newProfilePhoto: buildApiPhoto(action.photo) }),\n });\n }\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n const localDbChatId = resolveMessageApiChatId(update.message)!;\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = new GramJs.ChatPhotoEmpty();\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: { avatarHash: undefined },\n });\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && Boolean(e.self) && e.id === action.userId\n ))) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n 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 && Boolean(e.self) && action.users.includes(e.id)\n ))) {\n onUpdate({\n '@type': 'updateChatJoin',\n id: message.chatId,\n });\n }\n } else if (action instanceof GramJs.MessageActionGroupCall) {\n if (!action.duration && action.call) {\n onUpdate({\n '@type': 'updateGroupCallChatId',\n chatId: message.chatId,\n call: {\n id: action.call.id.toString(),\n accessHash: action.call.accessHash.toString(),\n },\n });\n }\n }\n }\n } else if (\n update instanceof GramJs.UpdateEditMessage\n || update instanceof GramJs.UpdateEditChannelMessage\n ) {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n const message = buildApiMessage(update.message)!;\n\n onUpdate({\n '@type': 'updateMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else if (update instanceof GramJs.UpdateMessageReactions) {\n onUpdate({\n '@type': 'updateMessageReactions',\n id: update.msgId,\n chatId: getApiChatIdFromMtpPeer(update.peer),\n reactions: buildMessageReactions(update.reactions),\n });\n } else if (update instanceof GramJs.UpdateDeleteMessages) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: update.messages,\n });\n } else if (update instanceof GramJs.UpdateDeleteScheduledMessages) {\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: update.messages,\n chatId: getApiChatIdFromMtpPeer(update.peer),\n });\n } else if (update instanceof GramJs.UpdateDeleteChannelMessages) {\n const chatId = buildApiPeerId(update.channelId, 'channel');\n const ids = update.messages;\n const existingIds = ids.filter((id) => localDb.messages[`${chatId}-${id}`]);\n const missingIds = ids.filter((id) => !localDb.messages[`${chatId}-${id}`]);\n const profilePhotoIds = ids.map((id) => {\n const message = localDb.messages[`${chatId}-${id}`];\n\n return message && message instanceof GramJs.MessageService && 'photo' in message.action\n ? String(message.action.photo.id)\n : undefined;\n }).filter(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 if (update.action instanceof GramJs.SendMessageEmojiInteraction) {\n onUpdate({\n '@type': 'updateStartEmojiInteraction',\n id,\n emoji: update.action.emoticon,\n messageId: update.action.msgId,\n interaction: buildApiEmojiInteraction(JSON.parse(update.action.interaction.data)),\n });\n } else {\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update, serverTimeOffset),\n });\n }\n } else if (update instanceof GramJs.UpdateChannelUserTyping) {\n const id = buildApiPeerId(update.channelId, 'channel');\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update, serverTimeOffset),\n });\n } else if (update instanceof GramJs.UpdateChannel) {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n const channel = _entities.find((e): e is GramJs.Channel | GramJs.ChannelForbidden => (\n e instanceof GramJs.Channel || e instanceof GramJs.ChannelForbidden\n ));\n\n if (channel instanceof GramJs.Channel) {\n if (shouldIgnoreNextChannelUpdate) {\n shouldIgnoreNextChannelUpdate = false;\n return;\n }\n\n if (originRequest instanceof GramJs.messages.ToggleNoForwards) {\n shouldIgnoreNextChannelUpdate = true;\n setTimeout(() => { shouldIgnoreNextChannelUpdate = false; }, IGNORE_NEXT_CHANNEL_UPDATE_TIMEOUT);\n }\n\n const chat = buildApiChatFromPreview(channel);\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n onUpdate({\n '@type': chat.isNotJoined ? 'updateChatLeave' : 'updateChatJoin',\n id: buildApiPeerId(update.channelId, 'channel'),\n });\n }\n } else if (channel instanceof GramJs.ChannelForbidden) {\n const chatId = buildApiPeerId(update.channelId, 'channel');\n\n onUpdate({\n '@type': 'updateChat',\n id: chatId,\n chat: {\n isRestricted: true,\n },\n });\n\n onUpdate({\n '@type': 'updateChatLeave',\n id: chatId,\n });\n } else if (_entities.length === 0) {\n // The link to the discussion group may have been changed.\n // No corresponding update available at this moment https://core.telegram.org/type/Updates\n onUpdate({\n '@type': 'resetMessages',\n id: buildApiPeerId(update.channelId, 'channel'),\n });\n }\n } else if (\n update instanceof GramJs.UpdateDialogUnreadMark\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n chat: {\n hasUnreadMark: update.unread,\n },\n });\n } else if (update instanceof GramJs.UpdateChatDefaultBannedRights) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n defaultBannedRights: omitVirtualClassFields(update.defaultBannedRights),\n },\n });\n\n // Users\n } else if (update instanceof GramJs.UpdateUserStatus) {\n onUpdate({\n '@type': 'updateUserStatus',\n userId: buildApiPeerId(update.userId, 'user'),\n status: buildApiUserStatus(update.status),\n });\n } else if (update instanceof GramJs.UpdateUserName) {\n const apiUserId = buildApiPeerId(update.userId, 'user');\n const updatedUser = localDb.users[apiUserId];\n const user = updatedUser?.mutualContact && !updatedUser.self\n ? pick(update, ['username'])\n : pick(update, ['firstName', 'lastName', 'username']);\n\n onUpdate({\n '@type': 'updateUser',\n id: apiUserId,\n user,\n });\n } else if (update instanceof GramJs.UpdateUserPhoto) {\n const { userId, photo } = update;\n const apiUserId = buildApiPeerId(userId, 'user');\n const avatarHash = buildAvatarHash(photo);\n\n if (localDb.users[apiUserId]) {\n localDb.users[apiUserId].photo = photo;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: apiUserId,\n user: { avatarHash },\n });\n } else if (update instanceof GramJs.UpdateUserPhone) {\n const { userId, phone } = update;\n\n onUpdate({\n '@type': 'updateUser',\n id: buildApiPeerId(userId, 'user'),\n user: { phoneNumber: phone },\n });\n } else if (update instanceof GramJs.UpdatePeerSettings) {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { _entities, settings } = update;\n if (!_entities) {\n return;\n }\n\n if (_entities?.length) {\n _entities\n .filter((e) => e instanceof GramJs.User && !e.contact)\n .forEach((user) => {\n onUpdate({\n '@type': 'deleteContact',\n id: buildApiPeerId(user.id, 'user'),\n });\n });\n\n _entities\n .filter((e) => e instanceof GramJs.User && e.contact)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user: {\n ...user,\n ...(settings && { settings: buildApiChatSettings(settings) }),\n },\n });\n });\n }\n\n // Settings\n } else if (update instanceof GramJs.UpdateNotifySettings) {\n const {\n notifySettings: {\n showPreviews, silent, muteUntil,\n },\n peer: { className },\n } = update;\n\n const peerType = className === 'NotifyUsers'\n ? 'contact'\n : (className === 'NotifyChats'\n ? 'group'\n : (className === 'NotifyBroadcasts'\n ? 'broadcast'\n : undefined\n )\n );\n\n if (!peerType) {\n return;\n }\n\n onUpdate({\n '@type': 'updateNotifySettings',\n peerType,\n isSilent: Boolean(silent\n || (typeof muteUntil === 'number' && Date.now() + serverTimeOffset * 1000 < muteUntil * 1000)),\n shouldShowPreviews: Boolean(showPreviews),\n });\n } else if (update instanceof GramJs.UpdatePeerBlocked) {\n onUpdate({\n '@type': 'updatePeerBlocked',\n id: getApiChatIdFromMtpPeer(update.peerId),\n isBlocked: update.blocked,\n });\n } else if (update instanceof GramJs.UpdatePrivacy) {\n const key = buildPrivacyKey(update.key);\n if (key) {\n onUpdate({\n '@type': 'updatePrivacy',\n key,\n rules: buildPrivacyRules(update.rules),\n });\n }\n\n // Misc\n } else if (update instanceof GramJs.UpdateDraftMessage) {\n onUpdate({\n '@type': 'draftMessage',\n chatId: getApiChatIdFromMtpPeer(update.peer),\n ...buildMessageDraft(update.draft),\n });\n } else if (update instanceof GramJs.UpdateContactsReset) {\n onUpdate({ '@type': 'updateResetContactList' });\n } else if (update instanceof GramJs.UpdateFavedStickers) {\n onUpdate({ '@type': 'updateFavoriteStickers' });\n } else if (update instanceof GramJs.UpdateGroupCall) {\n onUpdate({\n '@type': 'updateGroupCall',\n call: buildApiGroupCall(update.call),\n });\n } else if (update instanceof GramJs.UpdateGroupCallConnection) {\n onUpdate({\n '@type': 'updateGroupCallConnection',\n data: JSON.parse(update.params.data) as GroupCallConnectionData,\n presentation: Boolean(update.presentation),\n });\n } else if (update instanceof GramJs.UpdateGroupCallParticipants) {\n // eslint-disable-next-line no-underscore-dangle\n const entities = update._entities;\n if (entities) {\n addEntitiesWithPhotosToLocalDb(entities);\n dispatchUserAndChatUpdates(entities);\n }\n\n onUpdate({\n '@type': 'updateGroupCallParticipants',\n groupCallId: getGroupCallId(update.call),\n participants: update.participants.map(buildApiGroupCallParticipant),\n });\n } else if (update instanceof GramJs.UpdatePendingJoinRequests) {\n // eslint-disable-next-line no-underscore-dangle\n const entities = update._entities;\n if (entities) {\n addEntitiesWithPhotosToLocalDb(entities);\n dispatchUserAndChatUpdates(entities);\n }\n\n onUpdate({\n '@type': 'updatePendingJoinRequests',\n chatId: getApiChatIdFromMtpPeer(update.peer),\n recentRequesterIds: update.recentRequesters.map((id) => buildApiPeerId(id, 'user')),\n requestsPending: update.requestsPending,\n });\n } else if (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 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 { 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 'document'\n);\n\nconst MEDIA_ENTITY_TYPES = new Set(['msg', 'sticker', 'gif', 'wallpaper', 'photo', 'webDocument', 'document']);\nconst TGS_MIME_TYPE = 'application/x-tgsticker';\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 as string | Blob);\n const arrayBuffer = mediaFormat === ApiMediaFormat.Progressive ? parsed as ArrayBuffer : undefined;\n\n return {\n prepared,\n arrayBuffer,\n mimeType,\n fullSize,\n };\n}\n\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('staticMap')\n ? url.match(/(staticMap):([0-9-]+)(\\?.+)/)\n : url.startsWith('webDocument')\n ? url.match(/(webDocument):(.+)/)\n : url.match(\n /(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file|document)([-\\d\\w./]+)(?::\\d+)?(\\?size=\\w+)?/,\n );\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] === 'staticMap') {\n const accessHash = mediaMatch[2];\n const params = mediaMatch[3];\n const parsedParams = new URLSearchParams(params);\n const long = parsedParams.get('long');\n const lat = parsedParams.get('lat');\n const w = parsedParams.get('w');\n const h = parsedParams.get('h');\n const zoom = parsedParams.get('zoom');\n const scale = parsedParams.get('scale');\n const accuracyRadius = parsedParams.get('accuracy_radius');\n\n const data = await client.downloadStaticMap(accessHash, long, lat, w, h, zoom, scale, accuracyRadius);\n return {\n mimeType: 'image/png',\n data,\n };\n }\n\n if (mediaMatch[1] === 'avatar' || mediaMatch[1] === 'profile') {\n entityType = getEntityTypeById(entityId);\n } else {\n entityType = mediaMatch[1] as (\n 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'stickerSet' | 'photo' | 'webDocument' | 'document'\n );\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 case 'document':\n entity = localDb.documents[entityId];\n break;\n }\n\n if (!entity) {\n return undefined;\n }\n\n if (MEDIA_ENTITY_TYPES.has(entityType)) {\n if (mediaFormat === ApiMediaFormat.Stream) {\n onProgress!.acceptsBuffer = true;\n }\n\n const data = await client.downloadMedia(entity, {\n sizeType, start, end, progressCallback: onProgress, workers: DOWNLOAD_WORKERS,\n });\n let mimeType;\n let fullSize;\n\n if (entity instanceof GramJs.Message) {\n mimeType = getMessageMediaMimeType(entity, sizeType);\n if (entity.media instanceof GramJs.MessageMediaDocument && entity.media.document instanceof GramJs.Document) {\n fullSize = entity.media.document.size;\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 ? TGS_MIME_TYPE : 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.MessageMediaGeo\n || message.media instanceof GramJs.MessageMediaVenue\n || message.media instanceof GramJs.MessageMediaGeoLive) {\n return 'image/png';\n }\n\n if (message.media instanceof GramJs.MessageMediaDocument && message.media.document instanceof GramJs.Document) {\n if (sizeType) {\n return message.media.document!.attributes.some((a) => a instanceof GramJs.DocumentAttributeSticker)\n ? 'image/webp'\n : 'image/jpeg';\n }\n\n return message.media.document!.mimeType;\n }\n\n if (message.media instanceof GramJs.MessageMediaWebPage\n && message.media.webpage instanceof GramJs.WebPage\n && message.media.webpage.document instanceof GramJs.Document) {\n if (sizeType) {\n return 'image/jpeg';\n }\n\n return message.media.webpage.document.mimeType;\n }\n\n return undefined;\n}\n\n// eslint-disable-next-line no-async-without-await/no-async-without-await\nasync function parseMedia(\n data: Buffer, mediaFormat: ApiMediaFormat, mimeType?: string,\n): Promise {\n switch (mediaFormat) {\n case ApiMediaFormat.BlobUrl:\n case ApiMediaFormat.Lottie: {\n return new Blob([data], { type: mimeType });\n }\n case ApiMediaFormat.Progressive: {\n return data.buffer;\n }\n }\n\n return undefined;\n}\n\nfunction prepareMedia(mediaData: Exclude): 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, isWebmSupported,\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 // eslint-disable-next-line no-restricted-globals\n (self as any).isWebmSupported = isWebmSupported;\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: any) {\n // eslint-disable-next-line no-console\n console.error(err);\n\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 shouldReturnTrue: true,\n shouldThrow?: boolean,\n shouldIgnoreUpdates?: undefined,\n dcId?: number,\n): Promise;\n\nexport async function invokeRequest(\n request: T,\n shouldReturnTrue?: boolean,\n shouldThrow?: boolean,\n shouldIgnoreUpdates?: boolean,\n dcId?: number,\n): Promise;\n\nexport async function invokeRequest(\n request: T,\n shouldReturnTrue = false,\n shouldThrow = false,\n shouldIgnoreUpdates = false,\n dcId?: number,\n) {\n if (!isConnected) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(`[GramJs/client] INVOKE ERROR ${request.className}: Client is not connected`);\n }\n\n return undefined;\n }\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ${request.className}`);\n }\n\n const result = await client.invoke(request, dcId);\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE RESPONSE ${request.className}`, result);\n }\n\n if (!shouldIgnoreUpdates) {\n handleUpdatesFromRequest(request, result);\n }\n\n return shouldReturnTrue ? result && true : result;\n } catch (err: any) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ERROR ${request.className}`);\n // eslint-disable-next-line no-console\n console.error(err);\n }\n\n if (shouldThrow) {\n throw err;\n }\n\n dispatchErrorUpdate(err, request);\n\n return undefined;\n }\n}\n\nfunction handleUpdatesFromRequest(request: T, result: T['__response']) {\n let manyUpdates;\n let singleUpdate;\n\n if (result instanceof GramJs.UpdatesCombined || result instanceof GramJs.Updates) {\n manyUpdates = result;\n } else if (typeof result === 'object' && 'updates' in result && (\n result.updates instanceof GramJs.Updates || result.updates instanceof GramJs.UpdatesCombined\n )) {\n manyUpdates = result.updates;\n } else if (\n result instanceof GramJs.UpdateShortMessage\n || result instanceof GramJs.UpdateShortChatMessage\n || result instanceof GramJs.UpdateShort\n || result instanceof GramJs.UpdateShortSentMessage\n ) {\n singleUpdate = result;\n }\n\n if (manyUpdates) {\n injectUpdateEntities(manyUpdates);\n\n manyUpdates.updates.forEach((update) => {\n updater(update, request);\n });\n } else if (singleUpdate) {\n updater(singleUpdate, request);\n }\n}\n\nexport function downloadMedia(\n args: { url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number; isHtmlAllowed?: boolean },\n onProgress?: ApiOnProgress,\n) {\n return downloadMediaWithClient(args, client, isConnected, onProgress);\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: any) {\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 buildApiChatSettings,\n} from '../apiBuilders/chats';\nimport { buildApiMessage, buildMessageDraft } from '../apiBuilders/messages';\nimport { buildApiUser, buildApiUsersAndStatuses } from '../apiBuilders/users';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n buildInputEntity,\n buildInputPeer,\n buildMtpMessageEntity,\n buildFilterFromApiFolder,\n isMessageWithMedia,\n buildChatBannedRights,\n buildChatAdminRights,\n} from '../gramjsBuilders';\nimport { addEntitiesWithPhotosToLocalDb, addMessageToLocalDb, addPhotoToLocalDb } from '../helpers';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\nimport { buildApiPhoto } from '../apiBuilders/common';\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 fetchChatSettings(chat: ApiChat) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPeerSettings({\n peer: buildInputPeer(id, accessHash),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return buildApiChatSettings(result.settings);\n}\n\nexport async function searchChats({ query }: { query: string }) {\n const result = await invokeRequest(new GramJs.contacts.Search({ q: query }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const localPeerIds = result.myResults.map(getApiChatIdFromMtpPeer);\n const allChats = result.chats.concat(result.users)\n .map((user) => buildApiChatFromPreview(user))\n .filter(Boolean as any);\n const allUsers = result.users.map(buildApiUser).filter((user) => Boolean(user) && !user.isSelf) as ApiUser[];\n\n return {\n localChats: allChats.filter((r) => localPeerIds.includes(r.id)),\n localUsers: allUsers.filter((u) => localPeerIds.includes(u.id)),\n globalChats: allChats.filter((r) => !localPeerIds.includes(r.id)),\n globalUsers: allUsers.filter((u) => !localPeerIds.includes(u.id)),\n };\n}\n\nexport async function fetchChat({\n type, user,\n}: {\n type: 'user' | 'self' | 'support'; user?: ApiUser;\n}) {\n let mtpUser: GramJs.User | undefined;\n\n if (type === 'self' || type === 'user') {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: [\n type === 'user' && user\n ? buildInputEntity(user.id, user.accessHash) as GramJs.InputUser\n : new GramJs.InputUserSelf(),\n ],\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n [mtpUser] = result;\n } else if (type === 'support') {\n const result = await invokeRequest(new GramJs.help.GetSupport());\n if (!result || !result.user) {\n return undefined;\n }\n\n mtpUser = result.user;\n }\n\n const chat = buildApiChatFromPreview(mtpUser!, type === 'support');\n if (!chat) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n return { chatId: chat.id };\n}\n\nexport async function requestChatUpdate({\n chat,\n serverTimeOffset,\n lastLocalMessage,\n noLastMessage,\n}: {\n chat: ApiChat; serverTimeOffset: number; lastLocalMessage?: ApiMessage; noLastMessage?: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPeerDialogs({\n peers: [new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n })],\n }));\n\n if (!result) {\n return;\n }\n\n const dialog = result.dialogs[0];\n if (!dialog || !(dialog instanceof GramJs.Dialog)) {\n return;\n }\n\n const peersByKey = preparePeers(result);\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n if (!peerEntity) {\n return;\n }\n\n updateLocalDb(result);\n\n const lastRemoteMessage = buildApiMessage(result.messages[0]);\n const lastMessage = lastLocalMessage && (!lastRemoteMessage || (lastLocalMessage.date > lastRemoteMessage.date))\n ? lastLocalMessage\n : lastRemoteMessage;\n\n onUpdate({\n '@type': 'updateChat',\n id,\n chat: {\n ...buildApiChatFromDialog(dialog, peerEntity, serverTimeOffset),\n ...(!noLastMessage && { lastMessage }),\n },\n });\n}\n\nexport function saveDraft({\n chat,\n text,\n entities,\n replyToMsgId,\n}: {\n chat: ApiChat;\n text: string;\n entities?: ApiMessageEntity[];\n replyToMsgId?: number;\n}) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: text,\n ...(entities && {\n entities: entities.map(buildMtpMessageEntity),\n }),\n replyToMsgId,\n }));\n}\n\nexport function clearDraft(chat: ApiChat) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: '',\n }));\n}\n\nasync function getFullChatInfo(chatId: string): Promise<{\n fullInfo: ApiChatFullInfo;\n users?: ApiUser[];\n groupCall?: Partial;\n membersCount?: number;\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 availableReactions,\n recentRequesters,\n requestsPending,\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 enabledReactions: availableReactions,\n requestsPending,\n recentRequesterIds: recentRequesters?.map((userId) => buildApiPeerId(userId, 'user')),\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 membersCount: members?.length,\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 membersCount?: number;\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 canViewStats,\n linkedChatId,\n hiddenPrehistory,\n call,\n botInfo,\n availableReactions,\n defaultSendAs,\n requestsPending,\n recentRequesters,\n statsDc,\n participantsCount,\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 canViewStatistics: canViewStats,\n isPreHistoryHidden: hiddenPrehistory,\n members,\n kickedMembers,\n adminMembers,\n groupCallId: call ? String(call.id) : undefined,\n linkedChatId: linkedChatId ? buildApiPeerId(linkedChatId, 'chat') : undefined,\n botCommands,\n enabledReactions: availableReactions,\n sendAsId: defaultSendAs ? getApiChatIdFromMtpPeer(defaultSendAs) : undefined,\n requestsPending,\n recentRequesterIds: recentRequesters?.map((userId) => buildApiPeerId(userId, 'user')),\n statisticsDcId: statsDc,\n },\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 membersCount: participantsCount,\n };\n}\n\nexport async function updateChatMutedState({\n chat, isMuted, serverTimeOffset,\n}: {\n chat: ApiChat; isMuted: boolean; serverTimeOffset: number;\n}) {\n await invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer: new GramJs.InputNotifyPeer({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }),\n settings: new GramJs.InputPeerNotifySettings({ muteUntil: isMuted ? MAX_INT_32 : 0 }),\n }));\n\n onUpdate({\n '@type': 'updateNotifyExceptions',\n chatId: chat.id,\n isMuted,\n });\n\n void requestChatUpdate({\n chat,\n serverTimeOffset,\n noLastMessage: true,\n });\n}\n\nexport async function createChannel({\n title, about = '', users,\n}: {\n title: string; about?: string; users?: ApiUser[];\n}, noErrorUpdate = false): Promise {\n const result = await invokeRequest(new GramJs.channels.CreateChannel({\n broadcast: true,\n title,\n about,\n }));\n\n // `createChannel` can return a lot of different update types according to docs,\n // but currently channel creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n return undefined;\n }\n\n const newChannel = result.chats[0];\n if (!newChannel || !(newChannel instanceof GramJs.Channel)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created channel not found', result);\n }\n return undefined;\n }\n\n const channel = buildApiChatFromPreview(newChannel)!;\n\n if (users?.length) {\n try {\n await invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(channel.id, channel.accessHash) as GramJs.InputChannel,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }), undefined, noErrorUpdate);\n } catch (err) {\n // `noErrorUpdate` will cause an exception which we don't want either\n }\n }\n\n return channel;\n}\n\nexport function joinChannel({\n channelId, accessHash,\n}: {\n channelId: string; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.JoinChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\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 }), undefined, true);\n\n // `createChat` can return a lot of different update types according to docs,\n // but currently chat creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected chat creation update', result);\n }\n return undefined;\n }\n\n const newChat = result.chats[0];\n if (!newChat || !(newChat instanceof GramJs.Chat)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created chat not found', result);\n }\n return undefined;\n }\n\n return buildApiChatFromPreview(newChat);\n}\n\nexport async function editChatPhoto({\n chatId, accessHash, photo,\n}: {\n chatId: string; accessHash?: string; photo: File;\n}) {\n const uploadedPhoto = await uploadFile(photo);\n const inputEntity = buildInputEntity(chatId, accessHash);\n\n return invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditPhoto({\n channel: inputEntity as GramJs.InputChannel,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n })\n : new GramJs.messages.EditChatPhoto({\n chatId: inputEntity as BigInt.BigInteger,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n }),\n true,\n );\n}\n\nexport async function toggleChatPinned({\n chat,\n shouldBePinned,\n}: {\n chat: ApiChat;\n shouldBePinned: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.ToggleDialogPin({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n pinned: shouldBePinned || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: chat.id,\n isPinned: shouldBePinned,\n });\n }\n}\n\nexport function toggleChatArchived({\n chat, folderId,\n}: {\n chat: ApiChat; folderId: number;\n}) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.folders.EditPeerFolders({\n folderPeers: [new GramJs.InputFolderPeer({\n peer: buildInputPeer(id, accessHash),\n folderId,\n })],\n }), true);\n}\n\nexport async function fetchChatFolders() {\n const result = await invokeRequest(new GramJs.messages.GetDialogFilters());\n\n if (!result) {\n return undefined;\n }\n\n 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 getChatByPhoneNumber(phoneNumber: string) {\n const result = await invokeRequest(new GramJs.contacts.ResolvePhone({\n phone: phoneNumber,\n }));\n\n return processResolvedPeer(result);\n}\n\nexport async function getChatByUsername(username: string) {\n const result = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username,\n }));\n\n return processResolvedPeer(result);\n}\n\nfunction processResolvedPeer(result?: GramJs.contacts.TypeResolvedPeer) {\n if (!result) {\n return undefined;\n }\n\n const { users, chats } = result;\n\n const chat = chats.length\n ? buildApiChatFromPreview(chats[0])\n : buildApiChatFromPreview(users[0]);\n\n if (!chat) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return chat;\n}\n\nexport function togglePreHistoryHidden({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.TogglePreHistoryHidden({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\nexport function updateChatDefaultBannedRights({\n chat, bannedRights,\n}: { chat: ApiChat; bannedRights: ApiChatBannedRights }) {\n const { id, accessHash } = chat;\n const peer = buildInputPeer(id, accessHash);\n\n return invokeRequest(new GramJs.messages.EditChatDefaultBannedRights({\n peer,\n bannedRights: buildChatBannedRights(bannedRights),\n }), true);\n}\n\nexport function updateChatMemberBannedRights({\n chat, user, bannedRights, untilDate,\n}: { chat: ApiChat; user: ApiUser; bannedRights: ApiChatBannedRights; untilDate?: number }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const participant = buildInputPeer(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditBanned({\n channel,\n participant,\n bannedRights: buildChatBannedRights(bannedRights, untilDate),\n }), true);\n}\n\nexport function updateChatAdmin({\n chat, user, adminRights, customTitle = '',\n}: { chat: ApiChat; user: ApiUser; adminRights: ApiChatAdminRights; customTitle: string }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const userId = buildInputEntity(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditAdmin({\n channel,\n userId,\n adminRights: buildChatAdminRights(adminRights),\n rank: customTitle,\n }), true);\n}\n\nexport async function updateChatTitle(chat: ApiChat, title: string) {\n const inputEntity = buildInputEntity(chat.id, chat.accessHash);\n await invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditTitle({\n channel: inputEntity as GramJs.InputChannel,\n title,\n }) : new GramJs.messages.EditChatTitle({\n chatId: inputEntity as BigInt.BigInteger,\n title,\n }),\n true,\n );\n}\n\nexport async function updateChatAbout(chat: ApiChat, about: string) {\n const result = await invokeRequest(new GramJs.messages.EditChatAbout({\n peer: buildInputPeer(chat.id, chat.accessHash),\n about,\n }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n about,\n },\n });\n}\n\nexport function toggleSignatures({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.ToggleSignatures({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\ntype ChannelMembersFilter =\n 'kicked'\n | 'admin'\n | 'recent';\n\nexport async function fetchMembers(\n chatId: string,\n accessHash: string,\n memberFilter: ChannelMembersFilter = 'recent',\n offset?: number,\n) {\n let filter: GramJs.TypeChannelParticipantsFilter;\n\n switch (memberFilter) {\n case 'kicked':\n filter = new GramJs.ChannelParticipantsKicked({ q: '' });\n break;\n case 'admin':\n filter = new GramJs.ChannelParticipantsAdmins();\n break;\n default:\n filter = new GramJs.ChannelParticipantsRecent();\n break;\n }\n\n const result = await invokeRequest(new GramJs.channels.GetParticipants({\n channel: buildInputEntity(chatId, accessHash) as GramJs.InputChannel,\n filter,\n offset,\n limit: MEMBERS_LOAD_SLICE,\n }));\n\n if (!result || result instanceof GramJs.channels.ChannelParticipantsNotModified) {\n return undefined;\n }\n\n updateLocalDb(result);\n\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 }), true);\n}\n\nexport async function migrateChat(chat: ApiChat) {\n const result = await invokeRequest(\n new GramJs.messages.MigrateChat({ chatId: buildInputEntity(chat.id) as BigInt.BigInteger }),\n );\n\n // `migrateChat` can return a lot of different update types according to docs,\n // but currently chat migrations returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!result || !(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildApiChatFromPreview(result.chats[1]);\n}\n\nexport async function openChatByInvite(hash: string) {\n const result = await invokeRequest(new GramJs.messages.CheckChatInvite({ hash }));\n\n if (!result) {\n return undefined;\n }\n\n let chat: ApiChat | undefined;\n\n if (result instanceof GramJs.ChatInvite) {\n const {\n photo, participantsCount, title, channel, requestNeeded, about, megagroup,\n } = result;\n\n if (photo instanceof GramJs.Photo) {\n addPhotoToLocalDb(result.photo);\n }\n\n onUpdate({\n '@type': 'showInvite',\n data: {\n title,\n about,\n hash,\n participantsCount,\n isChannel: channel && !megagroup,\n isRequestNeeded: requestNeeded,\n ...(photo instanceof GramJs.Photo && { photo: buildApiPhoto(photo) }),\n },\n });\n } else {\n chat = buildApiChatFromPreview(result.chat);\n\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n }\n }\n\n if (!chat) {\n return undefined;\n }\n\n return { chatId: chat.id };\n}\n\nexport async function addChatMembers(chat: ApiChat, users: ApiUser[], noErrorUpdate = false) {\n try {\n if (chat.type === 'chatTypeChannel' || chat.type === 'chatTypeSuperGroup') {\n return await invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n users: users.map((user) => buildInputEntity(user.id, user.accessHash)) as GramJs.InputUser[],\n }), true, noErrorUpdate);\n }\n\n return await Promise.all(users.map((user) => {\n return invokeRequest(new GramJs.messages.AddChatUser({\n chatId: buildInputEntity(chat.id) as BigInt.BigInteger,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true, noErrorUpdate);\n }));\n } catch (err) {\n // `noErrorUpdate` will cause an exception which we don't want either\n return undefined;\n }\n}\n\nexport function deleteChatMember(chat: ApiChat, user: ApiUser) {\n if (chat.type === 'chatTypeChannel' || chat.type === 'chatTypeSuperGroup') {\n return updateChatMemberBannedRights({\n chat,\n user,\n bannedRights: {\n viewMessages: true,\n sendMessages: true,\n sendMedia: true,\n sendStickers: true,\n sendGifs: true,\n sendGames: true,\n sendInline: true,\n embedLinks: true,\n sendPolls: true,\n changeInfo: true,\n inviteUsers: true,\n pinMessages: true,\n },\n untilDate: MAX_INT_32,\n });\n } else {\n return invokeRequest(new GramJs.messages.DeleteChatUser({\n chatId: buildInputEntity(chat.id) as BigInt.BigInteger,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true);\n }\n}\n\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 }));\n if (!(updates instanceof GramJs.Updates) || !updates.chats.length) {\n return undefined;\n }\n\n return buildApiChatFromPreview(updates.chats[0]);\n}\n\nexport function setChatEnabledReactions({\n chat, enabledReactions,\n}: {\n chat: ApiChat; enabledReactions: string[];\n}) {\n return invokeRequest(new GramJs.messages.SetChatAvailableReactions({\n peer: buildInputPeer(chat.id, chat.accessHash),\n availableReactions: enabledReactions,\n }), true);\n}\n\nexport function toggleIsProtected({\n chat, isProtected,\n}: { chat: ApiChat; isProtected: boolean }) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.messages.ToggleNoForwards({\n peer: buildInputPeer(id, accessHash),\n enabled: isProtected,\n }), true);\n}\n","import { pause } from './schedulers';\n\n// Polyfill for Safari: `File` is not available in web worker\nif (typeof File === 'undefined') {\n // eslint-disable-next-line no-global-assign, no-restricted-globals, func-names\n self.File = class extends Blob {\n name: string;\n\n constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag) {\n if (options) {\n const { type, ...rest } = options;\n super(fileBits, { type });\n Object.assign(this, rest);\n } else {\n super(fileBits);\n }\n\n this.name = fileName;\n }\n } as typeof File;\n}\n\nexport function dataUriToBlob(dataUri: string) {\n const arr = dataUri.split(',');\n const mime = arr[0].match(/:(.*?);/)![1];\n const bstr = atob(arr[1]);\n let n = bstr.length;\n const u8arr = new Uint8Array(n);\n\n while (n--) {\n u8arr[n] = bstr.charCodeAt(n);\n }\n\n return new Blob([u8arr], { type: mime });\n}\n\nexport function blobToDataUri(blob: Blob): Promise {\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 ApiAttachment,\n ApiChat,\n ApiGlobalMessageSearchType,\n ApiMessage,\n ApiMessageEntity,\n ApiMessageSearchType,\n ApiNewPoll,\n ApiOnProgress,\n ApiReportReason,\n ApiSticker,\n ApiThreadInfo,\n ApiUser,\n ApiVideo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n OnApiUpdate,\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 buildLocalForwardedMessage,\n buildLocalMessage,\n buildWebPage,\n buildApiSponsoredMessage,\n} from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport {\n buildInputEntity,\n buildInputMediaDocument,\n buildInputPeer,\n buildInputPoll,\n buildInputReportReason,\n buildMtpMessageEntity,\n generateRandomBigInt,\n getEntityTypeById,\n isMessageWithMedia,\n isServiceMessageWithMedia,\n buildSendMessageAction,\n} from '../gramjsBuilders';\nimport localDb from '../localDb';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { fetchFile } from '../../../util/files';\nimport {\n addEntitiesWithPhotosToLocalDb,\n addMessageToLocalDb,\n deserializeBytes,\n resolveMessageApiChatId,\n} from '../helpers';\nimport { interpolateArray } from '../../../util/waveform';\nimport { requestChatUpdate } from './chats';\nimport { getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\n\nconst FAST_SEND_TIMEOUT = 1000;\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchMessages({\n chat,\n threadId,\n ...pagination\n}: {\n chat: ApiChat;\n threadId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n}) {\n const RequestClass = threadId === MAIN_THREAD_ID ? GramJs.messages.GetHistory : GramJs.messages.GetReplies;\n let result;\n\n try {\n result = await invokeRequest(new RequestClass({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(threadId !== MAIN_THREAD_ID && {\n msgId: threadId,\n }),\n ...pagination,\n }), undefined, true);\n } catch (err: any) {\n if (err.message === 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: {\n isRestricted: true,\n },\n });\n }\n }\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(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: any) {\n const { message } = err;\n\n // When fetching messages for the bot @replies, there may be situations when the user was banned\n // in the comment group or this group was deleted\n if (message !== 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'error',\n error: {\n message,\n isSlowMode: false,\n hasErrorKey: true,\n },\n });\n }\n }\n\n if (!result || result instanceof GramJs.messages.MessagesNotModified) {\n return undefined;\n }\n\n const mtpMessage = result.messages[0];\n if (!mtpMessage) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.MessageEmpty) {\n return MESSAGE_DELETED;\n }\n\n const message = mtpMessage && buildApiMessage(mtpMessage);\n if (!message) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.Message) {\n addMessageToLocalDb(mtpMessage);\n }\n\n const users = result.users.map(buildApiUser).filter(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,\n text,\n entities,\n replyingTo,\n attachment,\n sticker,\n gif,\n poll,\n contact,\n groupedId,\n scheduledAt,\n sendAs,\n serverTimeOffset,\n );\n onUpdate({\n '@type': localMessage.isScheduled ? 'newScheduledMessage' : 'newMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: localMessage,\n });\n\n // This is expected to arrive after `updateMessageSendSucceeded` which replaces the local ID,\n // so in most cases this will be simply ignored\n setTimeout(() => {\n onUpdate({\n '@type': localMessage.isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: {\n sendingState: 'messageSendingStatePending',\n },\n });\n }, FAST_SEND_TIMEOUT);\n\n const randomId = generateRandomBigInt();\n localDb.localMessages[String(randomId)] = localMessage;\n\n if (groupedId) {\n return sendGroupedMedia({\n chat, text, entities, replyingTo, attachment: attachment!, groupedId, isSilent, scheduledAt,\n }, randomId, localMessage, onProgress);\n }\n\n const prevQueue = queue;\n queue = (async () => {\n let media: GramJs.TypeInputMedia | undefined;\n if (attachment) {\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n await prevQueue;\n\n return;\n }\n } else if (sticker) {\n media = buildInputMediaDocument(sticker);\n } else if (gif) {\n media = buildInputMediaDocument(gif);\n } else if (poll) {\n media = buildInputPoll(poll, randomId);\n } else if (contact) {\n media = new GramJs.InputMediaContact({\n phoneNumber: contact.phoneNumber,\n firstName: contact.firstName,\n lastName: contact.lastName,\n vcard: '',\n });\n }\n\n await prevQueue;\n\n const RequestClass = media ? GramJs.messages.SendMedia : GramJs.messages.SendMessage;\n\n await invokeRequest(new RequestClass({\n clearDraft: true,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n peer: buildInputPeer(chat.id, chat.accessHash),\n randomId,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n ...(replyingTo && { replyToMsgId: replyingTo }),\n ...(media && { media }),\n ...(noWebPage && { noWebpage: noWebPage }),\n ...(sendAs && { sendAs: buildInputPeer(sendAs.id, sendAs.accessHash) }),\n }), true);\n })();\n\n return queue;\n}\n\nconst groupedUploads: Record;\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 chat, type, query, topMessageId, minDate, maxDate, ...pagination\n}: {\n chat: ApiChat;\n type?: ApiMessageSearchType | ApiGlobalMessageSearchType;\n query?: string;\n topMessageId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterRoundVoice();\n break;\n case 'profilePhoto':\n filter = new GramJs.InputMessagesFilterChatPhotos();\n break;\n case 'text':\n default: {\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.Search({\n peer: buildInputPeer(chat.id, chat.accessHash),\n filter,\n q: query || '',\n topMsgId: topMessageId,\n minDate,\n maxDate,\n ...pagination,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(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 nextOffsetId: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextOffsetId = messages[messages.length - 1].id;\n }\n }\n\n return {\n chats,\n users,\n messages,\n totalCount,\n nextOffsetId,\n };\n}\n\nexport async function searchMessagesGlobal({\n query, offsetRate = 0, limit, type = 'text', minDate, maxDate,\n}: {\n query: string;\n offsetRate?: number;\n limit: number;\n type?: ApiGlobalMessageSearchType;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterRoundVoice();\n break;\n case 'text':\n default: {\n if (!query && !(maxDate && minDate)) {\n return undefined;\n }\n\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.SearchGlobal({\n q: query,\n offsetRate,\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n filter,\n folderId: ALL_FOLDER_ID,\n minDate,\n maxDate,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb({\n chats: result.chats,\n users: result.users,\n messages: result.messages,\n } as GramJs.messages.Messages);\n\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(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 addEntitiesWithPhotosToLocalDb(result.users);\n addEntitiesWithPhotosToLocalDb(result.chats);\n\n result.messages.forEach((message) => {\n if ((message instanceof GramJs.Message && isMessageWithMedia(message))\n || (message instanceof GramJs.MessageService && isServiceMessageWithMedia(message))\n ) {\n addMessageToLocalDb(message);\n }\n });\n}\n\nexport async function fetchPinnedMessages({ chat }: { chat: ApiChat }) {\n const result = await invokeRequest(new GramJs.messages.Search(\n {\n peer: buildInputPeer(chat.id, chat.accessHash),\n filter: new GramJs.InputMessagesFilterPinned(),\n q: '',\n limit: PINNED_MESSAGES_LIMIT,\n },\n ));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(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 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 { addEntitiesWithPhotosToLocalDb, addPhotoToLocalDb, addUserToLocalDb } 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) => Boolean(user) && !user.isSelf) as ApiUser[];\n const ids = users.map(({ id }) => id);\n\n return {\n ids,\n users,\n };\n}\n\nexport async function fetchContactList() {\n const result = await invokeRequest(new GramJs.contacts.GetContacts({ hash: BigInt('0') }));\n if (!result || result instanceof GramJs.contacts.ContactsNotModified) {\n return undefined;\n }\n\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n addUserToLocalDb(user, true);\n }\n });\n\n 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 addUserToLocalDb(user, true);\n }\n });\n\n return buildApiUsersAndStatuses(result);\n}\n\nexport async function importContact({\n phone,\n firstName,\n lastName,\n}: {\n phone?: string;\n firstName?: string;\n lastName?: string;\n}) {\n const result = await invokeRequest(new GramJs.contacts.ImportContacts({\n contacts: [buildInputContact({\n phone: phone || '',\n firstName: firstName || '',\n lastName: lastName || '',\n })],\n }));\n\n if (result instanceof GramJs.contacts.ImportedContacts && result.users.length) {\n addUserToLocalDb(result.users[0]);\n }\n\n return result?.imported.length ? buildApiPeerId(result.imported[0].userId, 'user') : undefined;\n}\n\nexport function updateContact({\n id,\n accessHash,\n phoneNumber = '',\n firstName = '',\n lastName = '',\n shouldSharePhoneNumber = false,\n}: {\n id: string;\n accessHash?: string;\n phoneNumber?: string;\n firstName?: string;\n lastName?: string;\n shouldSharePhoneNumber?: boolean;\n}) {\n return invokeRequest(new GramJs.contacts.AddContact({\n id: buildInputEntity(id, accessHash) as GramJs.InputUser,\n firstName,\n lastName,\n phone: phoneNumber,\n ...(shouldSharePhoneNumber && { addPhonePrivacyException: shouldSharePhoneNumber }),\n }), true);\n}\n\nexport async function deleteContact({\n id,\n accessHash,\n}: {\n id: string;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const result = await invokeRequest(new GramJs.contacts.DeleteContacts({ id: [input] }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteContact',\n id,\n });\n}\n\nexport async function fetchProfilePhotos(user?: ApiUser, chat?: ApiChat) {\n if (user) {\n const { id, accessHash } = user;\n\n const result = await invokeRequest(new GramJs.photos.GetUserPhotos({\n userId: buildInputEntity(id, accessHash) as GramJs.InputUser,\n limit: PROFILE_PHOTOS_LIMIT,\n offset: 0,\n maxId: BigInt('0'),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n photos: result.photos\n .filter((photo): photo is GramJs.Photo => photo instanceof GramJs.Photo)\n .map(buildApiPhoto),\n };\n }\n\n const result = await searchMessagesLocal({\n chat: chat!,\n type: 'profilePhoto',\n limit: PROFILE_PHOTOS_LIMIT,\n });\n\n if (!result) {\n return undefined;\n }\n\n const { messages, users } = result;\n\n return {\n photos: messages.map((message) => message.content.action!.photo).filter(Boolean as any),\n users,\n };\n}\n\nexport function reportSpam(userOrChat: ApiUser | ApiChat) {\n const { id, accessHash } = userOrChat;\n\n return invokeRequest(new GramJs.messages.ReportSpam({\n peer: buildInputPeer(id, accessHash),\n }), true);\n}\n\nfunction updateLocalDb(result: (GramJs.photos.Photos | GramJs.photos.PhotosSlice | GramJs.messages.Chats)) {\n if ('chats' in result) {\n addEntitiesWithPhotosToLocalDb(result.chats);\n }\n\n if ('photos' in result) {\n result.photos.forEach(addPhotoToLocalDb);\n }\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { 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 fetchAnimatedEmojiEffects() {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: new GramJs.InputStickerSetAnimatedEmojiAnimations(),\n }));\n\n if (!(result instanceof GramJs.messages.StickerSet)) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n };\n}\n\nexport async function searchStickers({ query, hash = '0' }: { query: string; hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.SearchStickerSets({\n q: query,\n hash: BigInt(hash),\n }));\n\n if (!result || result instanceof GramJs.messages.FoundStickerSetsNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function fetchSavedGifs({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetSavedGifs({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.SavedGifsNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n gifs: processGifResult(result.gifs),\n };\n}\n\nexport function saveGif({ gif, shouldUnsave }: { gif: ApiVideo; shouldUnsave?: boolean }) {\n const request = new GramJs.messages.SaveGif({\n id: buildInputDocument(gif),\n unsave: shouldUnsave,\n });\n\n return invokeRequest(request, true);\n}\n\nexport async function installStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.InstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: Date.now() },\n });\n }\n}\n\nexport async function uninstallStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.UninstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: undefined },\n });\n }\n}\n\nlet inputGifBot: GramJs.InputUser | undefined;\n\nexport async function searchGifs({ query, offset = '' }: { query: string; offset?: string }) {\n if (!inputGifBot) {\n const config = await invokeRequest(new GramJs.help.GetConfig());\n if (!config) {\n return undefined;\n }\n\n const resolvedPeer = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username: config.gifSearchUsername,\n }));\n if (!resolvedPeer || !(resolvedPeer.users[0] instanceof GramJs.User)) {\n return undefined;\n }\n\n inputGifBot = new GramJs.InputUser({\n userId: (resolvedPeer.peer as GramJs.PeerUser).userId,\n accessHash: resolvedPeer.users[0].accessHash!,\n });\n }\n\n const result = await invokeRequest(new GramJs.messages.GetInlineBotResults({\n bot: inputGifBot,\n peer: new GramJs.InputPeerEmpty(),\n query,\n offset,\n }));\n if (!result) {\n return undefined;\n }\n\n const documents = result.results\n .map((foundGif) => {\n if (foundGif instanceof GramJs.BotInlineMediaResult) {\n return foundGif.document;\n }\n\n return undefined;\n })\n .filter(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, ApiUser, OnApiUpdate } from '../../types';\nimport { addEntitiesWithPhotosToLocalDb } from '../helpers';\nimport { buildApiExportedInvite, buildChatInviteImporter } from '../apiBuilders/chats';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport function checkChatUsername({ username }: { username: string }) {\n return invokeRequest(new GramJs.channels.CheckUsername({\n channel: new GramJs.InputChannelEmpty(),\n username,\n }));\n}\n\nexport async function setChatUsername(\n { chat, username }: { chat: ApiChat; username: string },\n) {\n const result = await invokeRequest(new GramJs.channels.UpdateUsername({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n username,\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { username },\n });\n }\n}\n\nexport async function updatePrivateLink({\n chat, usageLimit, expireDate,\n}: {\n chat: ApiChat; usageLimit?: number; expireDate?: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.ExportChatInvite({\n peer: buildInputPeer(chat.id, chat.accessHash),\n usageLimit,\n expireDate,\n }));\n\n 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\nexport async function fetchExportedChatInvites({\n peer, admin, limit = 0, isRevoked,\n}: { peer: ApiChat; admin: ApiUser; limit: number; isRevoked?: boolean }) {\n const exportedInvites = await invokeRequest(new GramJs.messages.GetExportedChatInvites({\n peer: buildInputPeer(peer.id, peer.accessHash),\n adminId: buildInputEntity(admin.id, admin.accessHash) as GramJs.InputUser,\n limit,\n revoked: isRevoked || undefined,\n }));\n\n if (!exportedInvites) return undefined;\n addEntitiesWithPhotosToLocalDb(exportedInvites.users);\n return exportedInvites.invites.map(buildApiExportedInvite);\n}\n\nexport async function editExportedChatInvite({\n peer, isRevoked, link, expireDate, usageLimit, isRequestNeeded, title,\n}: {\n peer: ApiChat;\n isRevoked?: boolean;\n link: string;\n expireDate?: number;\n usageLimit?: number;\n isRequestNeeded?: boolean;\n title?: string;\n}) {\n const invite = await invokeRequest(new GramJs.messages.EditExportedChatInvite({\n link,\n peer: buildInputPeer(peer.id, peer.accessHash),\n expireDate,\n usageLimit: !isRequestNeeded ? usageLimit : undefined,\n requestNeeded: isRequestNeeded,\n title,\n revoked: isRevoked || undefined,\n }));\n\n if (!invite) return undefined;\n\n addEntitiesWithPhotosToLocalDb(invite.users);\n if (invite instanceof GramJs.messages.ExportedChatInvite) {\n const replaceInvite = buildApiExportedInvite(invite.invite);\n return {\n oldInvite: replaceInvite,\n newInvite: replaceInvite,\n };\n }\n\n if (invite instanceof GramJs.messages.ExportedChatInviteReplaced) {\n const oldInvite = buildApiExportedInvite(invite.invite);\n const newInvite = buildApiExportedInvite(invite.newInvite);\n return {\n oldInvite,\n newInvite,\n };\n }\n return undefined;\n}\n\nexport async function exportChatInvite({\n peer, expireDate, usageLimit, isRequestNeeded, title,\n}: {\n peer: ApiChat;\n expireDate?: number;\n usageLimit?: number;\n isRequestNeeded?: boolean;\n title?: string;\n}) {\n const invite = await invokeRequest(new GramJs.messages.ExportChatInvite({\n peer: buildInputPeer(peer.id, peer.accessHash),\n expireDate,\n usageLimit: !isRequestNeeded ? usageLimit : undefined,\n requestNeeded: isRequestNeeded || undefined,\n title,\n }));\n\n if (!invite) return undefined;\n return buildApiExportedInvite(invite);\n}\n\nexport async function deleteExportedChatInvite({\n peer, link,\n}: {\n peer: ApiChat; link: string;\n}) {\n const result = await invokeRequest(new GramJs.messages.DeleteExportedChatInvite({\n peer: buildInputPeer(peer.id, peer.accessHash),\n link,\n }));\n\n return result;\n}\n\nexport async function deleteRevokedExportedChatInvites({\n peer, admin,\n}: {\n peer: ApiChat; admin: ApiUser;\n}) {\n const result = await invokeRequest(new GramJs.messages.DeleteRevokedExportedChatInvites({\n peer: buildInputPeer(peer.id, peer.accessHash),\n adminId: buildInputEntity(admin.id, admin.accessHash) as GramJs.InputUser,\n }));\n\n return result;\n}\n\nexport async function fetchChatInviteImporters({\n peer, link, offsetDate = 0, offsetUser, limit = 0, isRequested,\n}: {\n peer: ApiChat; link?: string; offsetDate: number; offsetUser?: ApiUser; limit: number; isRequested?: boolean;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetChatInviteImporters({\n peer: buildInputPeer(peer.id, peer.accessHash),\n link,\n offsetDate,\n offsetUser: offsetUser\n ? buildInputEntity(offsetUser.id, offsetUser.accessHash) as GramJs.InputUser : new GramJs.InputUserEmpty(),\n limit,\n requested: isRequested || undefined,\n }));\n\n if (!result) return undefined;\n addEntitiesWithPhotosToLocalDb(result.users);\n return result.importers.map((importer) => buildChatInviteImporter(importer));\n}\n\nexport function hideChatJoinRequest({\n peer,\n user,\n isApproved,\n}: {\n peer: ApiChat;\n user: ApiUser;\n isApproved: boolean;\n}) {\n return invokeRequest(new GramJs.messages.HideChatJoinRequest({\n peer: buildInputPeer(peer.id, peer.accessHash),\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n approved: isApproved || undefined,\n }), true);\n}\n\nexport function hideAllChatJoinRequests({\n peer,\n isApproved,\n link,\n}: {\n peer: ApiChat;\n isApproved: boolean;\n link?: string;\n}) {\n return invokeRequest(new GramJs.messages.HideAllChatJoinRequests({\n peer: buildInputPeer(peer.id, peer.accessHash),\n approved: isApproved || undefined,\n link,\n }), true);\n}\n\nexport function hideChatReportPanel(chat: ApiChat) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.messages.HidePeerSettingsBar({\n peer: buildInputPeer(id, accessHash),\n }));\n}\n","import { Api as GramJs, errors } from '../../../lib/gramjs';\n\nimport { 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: any) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function clearPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ currentPassword });\n\n return true;\n } catch (err: any) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updatePassword(currentPassword: string, password: string, hint?: string, email?: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: password,\n hint,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err: any) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updateRecoveryEmail(currentPassword: string, email: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: currentPassword,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err: any) {\n onError(err);\n\n return false;\n }\n}\n\nexport function provideRecoveryEmailCode(code: string) {\n emailCodeController.resolve!(code);\n}\n\nfunction onError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateTwoFaError',\n message,\n });\n}\n","import { 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 }));\n\n if (!result) return undefined;\n\n if (result instanceof GramJs.Updates) {\n const update = result.updates.find((u) => u instanceof GramJs.UpdateGroupCall);\n if (!(update instanceof GramJs.UpdateGroupCall)) return undefined;\n\n return buildApiGroupCall(update.call);\n }\n\n return undefined;\n}\n\nexport async function createGroupCall({\n peer,\n}: {\n peer: ApiChat;\n}) {\n const randomId = generateRandomInt();\n const result = await invokeRequest(new GramJs.phone.CreateGroupCall({\n peer: buildInputPeer(peer.id, peer.accessHash),\n randomId,\n }));\n\n if (!result) return undefined;\n\n if (result instanceof GramJs.Updates) {\n const update = result.updates[0];\n if (update instanceof GramJs.UpdateGroupCall) {\n return buildApiGroupCall(update.call);\n }\n }\n\n return undefined;\n}\n\nexport function joinGroupCallPresentation({\n call, params,\n}: {\n call: ApiGroupCall; params: JoinGroupCallPayload;\n}) {\n return invokeRequest(new GramJs.phone.JoinGroupCallPresentation({\n call: buildInputGroupCall(call),\n params: new GramJs.DataJSON({\n data: JSON.stringify(params),\n }),\n }), true);\n}\n\nexport function toggleGroupCallStartSubscription({\n call, subscribed,\n}: {\n call: ApiGroupCall; subscribed: boolean;\n}) {\n return invokeRequest(new GramJs.phone.ToggleGroupCallStartSubscription({\n call: buildInputGroupCall(call),\n subscribed,\n }), true);\n}\n\nexport function leaveGroupCallPresentation({\n call,\n}: {\n call: ApiGroupCall;\n}) {\n return invokeRequest(new GramJs.phone.LeaveGroupCallPresentation({\n call: buildInputGroupCall(call),\n }), true);\n}\n","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, OnApiUpdate } from '../../types';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\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 async 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 const result = await 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 }));\n\n if (result instanceof GramJs.payments.PaymentVerificationNeeded) {\n onUpdate({\n '@type': 'updatePaymentVerificationNeeded',\n url: result.url,\n });\n\n return undefined;\n }\n\n return Boolean(result);\n}\n\nexport async function getPaymentForm({\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 { 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 publicToken: nativeData?.public_token,\n },\n };\n}\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport BigInt from 'big-integer';\nimport localDb from '../localDb';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiAppConfig } from '../../types';\nimport { buildJson } from './misc';\n\ntype GramJsAppConfig = {\n emojies_sounds: Record;\n emojies_send_dice: string[];\n groupcall_video_participants_max: number;\n reactions_default: string;\n reactions_uniq_max: number;\n chat_read_mark_size_threshold: number;\n chat_read_mark_expire_period: number;\n};\n\nfunction buildEmojiSounds(appConfig: GramJsAppConfig) {\n const { emojies_sounds } = appConfig;\n return Object.keys(emojies_sounds).reduce((acc: Record, key) => {\n const l = emojies_sounds[key];\n localDb.documents[l.id] = new GramJs.Document({\n id: BigInt(l.id),\n accessHash: BigInt(l.access_hash),\n dcId: 1,\n mimeType: 'audio/ogg',\n fileReference: Buffer.from(atob(l.file_reference_base64\n .replace(/-/g, '+')\n .replace(/_/g, '/'))),\n } as GramJs.Document);\n\n acc[key] = l.id;\n return acc;\n }, {});\n}\n\nexport function buildApiConfig(json: GramJs.TypeJSONValue): ApiAppConfig {\n const appConfig = buildJson(json) as GramJsAppConfig;\n\n return {\n emojiSounds: buildEmojiSounds(appConfig),\n defaultReaction: appConfig.reactions_default,\n seenByMaxChatMembers: appConfig.chat_read_mark_size_threshold,\n seenByExpiresAt: appConfig.chat_read_mark_expire_period,\n };\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport {\n ApiAppConfig,\n ApiChat,\n ApiLangString,\n ApiLanguage,\n ApiNotifyException,\n ApiUser,\n ApiWallpaper,\n} from '../../types';\nimport { ApiPrivacyKey, InputPrivacyRules, LangCode } from '../../../types';\n\nimport { BLOCKED_LIST_LIMIT, DEFAULT_LANG_PACK, LANG_PACKS } from '../../../config';\nimport {\n buildApiCountryList,\n buildApiNotifyException,\n buildApiSession,\n buildApiWallpaper,\n buildPrivacyRules,\n} from '../apiBuilders/misc';\n\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildInputEntity, buildInputPeer, buildInputPrivacyKey } from '../gramjsBuilders';\nimport { getClient, invokeRequest, uploadFile } from './client';\nimport { omitVirtualClassFields } from '../apiBuilders/helpers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { getServerTime } from '../../../util/serverTime';\nimport { getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\nimport localDb from '../localDb';\nimport { buildApiConfig } from '../apiBuilders/appConfig';\nimport { addEntitiesWithPhotosToLocalDb } from '../helpers';\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 }), true);\n}\n\nexport function checkUsername(username: string) {\n return invokeRequest(new GramJs.account.CheckUsername({ username }));\n}\n\nexport function updateUsername(username: string) {\n return invokeRequest(new GramJs.account.UpdateUsername({ username }), true);\n}\n\nexport async function updateProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n return invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }), true);\n}\n\nexport async function uploadProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n await invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function fetchWallpapers() {\n const result = await invokeRequest(new GramJs.account.GetWallPapers({ hash: BigInt('0') }));\n\n if (!result || result instanceof GramJs.account.WallPapersNotModified) {\n return undefined;\n }\n\n const filteredWallpapers = result.wallpapers.filter((wallpaper) => {\n if (\n !(wallpaper instanceof GramJs.WallPaper)\n || !(wallpaper.document instanceof GramJs.Document)\n ) {\n return false;\n }\n\n return !wallpaper.pattern && wallpaper.document.mimeType !== 'application/x-tgwallpattern';\n }) as GramJs.WallPaper[];\n\n filteredWallpapers.forEach((wallpaper) => {\n localDb.documents[String(wallpaper.document.id)] = wallpaper.document as GramJs.Document;\n });\n\n return {\n wallpapers: filteredWallpapers.map(buildApiWallpaper).filter(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({\n compareSound: true,\n }), undefined, undefined, true);\n\n if (!(result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined)) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return result.updates.reduce((acc, update) => {\n if (!(update instanceof GramJs.UpdateNotifySettings && update.peer instanceof GramJs.NotifyPeer)) {\n return acc;\n }\n\n acc.push(buildApiNotifyException(update.notifySettings, update.peer.peer, serverTimeOffset));\n\n return acc;\n }, [] as ApiNotifyException[]);\n}\n\nexport async function fetchNotificationSettings({\n serverTimeOffset,\n}: { serverTimeOffset: number }) {\n const [\n isMutedContactSignUpNotification,\n privateContactNotificationsSettings,\n groupNotificationsSettings,\n broadcastNotificationsSettings,\n ] = await Promise.all([\n invokeRequest(new GramJs.account.GetContactSignUpNotification()),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyUsers(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyChats(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyBroadcasts(),\n })),\n ]);\n\n if (!privateContactNotificationsSettings || !groupNotificationsSettings || !broadcastNotificationsSettings) {\n return false;\n }\n\n const {\n silent: privateSilent, muteUntil: privateMuteUntil, showPreviews: privateShowPreviews,\n } = privateContactNotificationsSettings;\n const {\n silent: groupSilent, muteUntil: groupMuteUntil, showPreviews: groupShowPreviews,\n } = groupNotificationsSettings;\n const {\n silent: broadcastSilent, muteUntil: broadcastMuteUntil, showPreviews: broadcastShowPreviews,\n } = broadcastNotificationsSettings;\n\n return {\n hasContactJoinedNotifications: !isMutedContactSignUpNotification,\n hasPrivateChatsNotifications: !(\n privateSilent\n || (typeof privateMuteUntil === 'number' && getServerTime(serverTimeOffset) < privateMuteUntil)\n ),\n hasPrivateChatsMessagePreview: privateShowPreviews,\n hasGroupNotifications: !(\n groupSilent || (typeof groupMuteUntil === 'number'\n && getServerTime(serverTimeOffset) < groupMuteUntil)\n ),\n hasGroupMessagePreview: groupShowPreviews,\n hasBroadcastNotifications: !(\n broadcastSilent || (typeof broadcastMuteUntil === 'number'\n && getServerTime(serverTimeOffset) < broadcastMuteUntil)\n ),\n hasBroadcastMessagePreview: broadcastShowPreviews,\n };\n}\n\nexport function updateContactSignUpNotification(isSilent: boolean) {\n return invokeRequest(new GramJs.account.SetContactSignUpNotification({ silent: isSilent }));\n}\n\nexport function updateNotificationSettings(peerType: 'contact' | 'group' | 'broadcast', {\n isSilent,\n shouldShowPreviews,\n}: {\n isSilent: boolean;\n shouldShowPreviews: boolean;\n}) {\n let peer: GramJs.TypeInputNotifyPeer;\n if (peerType === 'contact') {\n peer = new GramJs.InputNotifyUsers();\n } else if (peerType === 'group') {\n peer = new GramJs.InputNotifyChats();\n } else {\n peer = new GramJs.InputNotifyBroadcasts();\n }\n\n const settings = {\n showPreviews: shouldShowPreviews,\n silent: isSilent,\n muteUntil: isSilent ? MAX_INT_32 : 0,\n };\n\n return invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer,\n settings: new GramJs.InputPeerNotifySettings(settings),\n }));\n}\n\nexport async function fetchLanguages(): Promise {\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()) as typeof collections[0] };\n}\n\nexport async function fetchLangStrings({ langPack, langCode, keys }: {\n langPack: string; langCode: string; keys: string[];\n}) {\n const result = await invokeRequest(new GramJs.langpack.GetStrings({\n langPack,\n langCode: BETA_LANG_CODES.includes(langCode) ? `${langCode}-raw` : langCode,\n keys,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return result.map(omitVirtualClassFields);\n}\n\nexport async function fetchPrivacySettings(privacyKey: ApiPrivacyKey) {\n const key = buildInputPrivacyKey(privacyKey);\n const result = await invokeRequest(new GramJs.account.GetPrivacy({ key }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nexport function registerDevice(token: string) {\n const client = getClient();\n const secret = client.session.getAuthKey().getKey();\n return invokeRequest(new GramJs.account.RegisterDevice({\n tokenType: 10,\n secret,\n appSandbox: false,\n otherUids: [],\n token,\n }));\n}\n\nexport function unregisterDevice(token: string) {\n return invokeRequest(new GramJs.account.UnregisterDevice({\n tokenType: 10,\n otherUids: [],\n token,\n }));\n}\n\nexport async function setPrivacySettings(\n privacyKey: ApiPrivacyKey, rules: InputPrivacyRules,\n) {\n const key = buildInputPrivacyKey(privacyKey);\n const privacyRules: GramJs.TypeInputPrivacyRule[] = [];\n\n if (rules.allowedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowUsers({\n users: rules.allowedUsers.map(({ id, accessHash }) => buildInputEntity(id, accessHash) as GramJs.InputUser),\n }));\n }\n if (rules.allowedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowChatParticipants({\n chats: rules.allowedChats.map(({ id }) => buildInputEntity(id) as BigInt.BigInteger),\n }));\n }\n if (rules.blockedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowUsers({\n users: rules.blockedUsers.map(({ id, accessHash }) => buildInputEntity(id, accessHash) as GramJs.InputUser),\n }));\n }\n if (rules.blockedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowChatParticipants({\n chats: rules.blockedChats.map(({ id }) => buildInputEntity(id) as BigInt.BigInteger),\n }));\n }\n switch (rules.visibility) {\n case 'everybody':\n privacyRules.push(new GramJs.InputPrivacyValueAllowAll());\n break;\n\n case 'contacts':\n privacyRules.push(new GramJs.InputPrivacyValueAllowContacts());\n break;\n\n case 'nonContacts':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowContacts());\n break;\n\n case 'nobody':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowAll());\n break;\n }\n\n const result = await invokeRequest(new GramJs.account.SetPrivacy({ key, rules: privacyRules }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nexport async function updateIsOnline(isOnline: boolean) {\n await invokeRequest(new GramJs.account.UpdateStatus({ offline: !isOnline }));\n}\n\nexport async function fetchContentSettings() {\n const result = await invokeRequest(new GramJs.account.GetContentSettings());\n if (!result) {\n return undefined;\n }\n\n return {\n isSensitiveEnabled: Boolean(result.sensitiveEnabled),\n canChangeSensitive: Boolean(result.sensitiveCanChange),\n };\n}\n\nexport function updateContentSettings(isEnabled: boolean) {\n return invokeRequest(new GramJs.account.SetContentSettings({\n sensitiveEnabled: isEnabled || undefined,\n }));\n}\n\nexport async function fetchAppConfig(): Promise {\n const result = await invokeRequest(new GramJs.help.GetAppConfig());\n if (!result) return undefined;\n\n return buildApiConfig(result);\n}\n\nfunction updateLocalDb(\n result: (\n GramJs.account.PrivacyRules | GramJs.contacts.Blocked | GramJs.contacts.BlockedSlice |\n GramJs.Updates | GramJs.UpdatesCombined\n ),\n) {\n addEntitiesWithPhotosToLocalDb(result.users);\n addEntitiesWithPhotosToLocalDb(result.chats);\n}\n\nexport async function fetchCountryList({ langCode = 'en' }: { langCode?: LangCode }) {\n const countryList = await invokeRequest(new GramJs.help.GetCountriesList({\n langCode,\n }));\n\n if (!(countryList instanceof GramJs.help.CountriesList)) {\n return undefined;\n }\n return buildApiCountryList(countryList.countries);\n}\n","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';\nimport { omitVirtualClassFields } from '../apiBuilders/helpers';\n\nexport function init() {\n}\n\nexport async function answerCallbackButton({\n chatId, accessHash, messageId, data,\n}: {\n chatId: string; accessHash?: string; messageId: number; data: string;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetBotCallbackAnswer({\n peer: buildInputPeer(chatId, accessHash),\n msgId: messageId,\n data: deserializeBytes(data),\n }));\n\n return result ? omitVirtualClassFields(result) : undefined;\n}\n\nexport async function fetchTopInlineBots() {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\n botsInline: true,\n }));\n\n if (!(topPeers instanceof GramJs.contacts.TopPeers)) {\n return undefined;\n }\n\n const users = topPeers.users.map(buildApiUser).filter(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, isSilent, scheduleDate,\n}: {\n chat: ApiChat;\n resultId: string;\n queryId: string;\n replyingTo?: number;\n sendAs?: ApiUser | ApiChat;\n isSilent?: boolean;\n scheduleDate?: number;\n}) {\n const randomId = generateRandomBigInt();\n\n await invokeRequest(new GramJs.messages.SendInlineBotResult({\n clearDraft: true,\n randomId,\n queryId: BigInt(queryId),\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: resultId,\n scheduleDate,\n ...(isSilent && { silent: true }),\n ...(replyingTo && { replyToMsgId: replyingTo }),\n ...(sendAs && { sendAs: buildInputPeer(sendAs.id, sendAs.accessHash) }),\n }), true);\n}\n\nexport async function startBot({\n bot, startParam,\n}: {\n bot: ApiUser;\n startParam?: string;\n}) {\n const randomId = generateRandomBigInt();\n\n await invokeRequest(new GramJs.messages.StartBot({\n bot: buildInputPeer(bot.id, bot.accessHash),\n peer: buildInputPeer(bot.id, bot.accessHash),\n randomId,\n startParam,\n }), true);\n}\n\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 { ApiChat, ApiUser } from '../../types';\nimport { invokeRequest } from './client';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { buildInputPeer } from '../gramjsBuilders';\nimport localDb from '../localDb';\nimport { buildApiAvailableReaction, buildMessagePeerReaction } from '../apiBuilders/messages';\nimport { REACTION_LIST_LIMIT } from '../../../config';\nimport { addEntitiesWithPhotosToLocalDb } from '../helpers';\nimport { buildApiUser } from '../apiBuilders/users';\n\nexport function sendWatchingEmojiInteraction({\n chat,\n emoticon,\n}: {\n chat: ApiChat; emoticon: string;\n}) {\n return invokeRequest(new GramJs.messages.SetTyping({\n peer: buildInputPeer(chat.id, chat.accessHash),\n action: new GramJs.SendMessageEmojiInteractionSeen({\n emoticon,\n }),\n }));\n}\n\nexport function sendEmojiInteraction({\n chat,\n emoticon,\n messageId,\n timestamps,\n}: {\n chat: ApiChat; messageId: number; emoticon: string; timestamps: number[];\n}) {\n return invokeRequest(new GramJs.messages.SetTyping({\n peer: buildInputPeer(chat.id, chat.accessHash),\n action: new GramJs.SendMessageEmojiInteraction({\n emoticon,\n msgId: messageId,\n interaction: new GramJs.DataJSON({\n data: JSON.stringify({\n v: 1,\n a: timestamps.map((t: number) => ({\n t,\n i: 1,\n })),\n }),\n }),\n }),\n }));\n}\n\nexport async function getAvailableReactions() {\n const result = await invokeRequest(new GramJs.messages.GetAvailableReactions({}));\n\n if (!result || result instanceof GramJs.messages.AvailableReactionsNotModified) {\n return undefined;\n }\n\n result.reactions.forEach((reaction) => {\n if (reaction.staticIcon instanceof GramJs.Document) {\n localDb.documents[String(reaction.staticIcon.id)] = reaction.staticIcon;\n }\n if (reaction.selectAnimation instanceof GramJs.Document) {\n localDb.documents[String(reaction.selectAnimation.id)] = reaction.selectAnimation;\n }\n if (reaction.aroundAnimation instanceof GramJs.Document) {\n localDb.documents[String(reaction.aroundAnimation.id)] = reaction.aroundAnimation;\n }\n if (reaction.centerIcon instanceof GramJs.Document) {\n localDb.documents[String(reaction.centerIcon.id)] = reaction.centerIcon;\n }\n });\n\n return result.reactions.map(buildApiAvailableReaction);\n}\n\nexport function sendReaction({\n chat, messageId, reaction,\n}: {\n chat: ApiChat; messageId: number; reaction?: string;\n}) {\n return invokeRequest(new GramJs.messages.SendReaction({\n ...(reaction && { reaction }),\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n }), true);\n}\n\nexport function fetchMessageReactions({\n ids, chat,\n}: {\n ids: number[]; chat: ApiChat;\n}) {\n return invokeRequest(new GramJs.messages.GetMessagesReactions({\n id: ids,\n peer: buildInputPeer(chat.id, chat.accessHash),\n }), true);\n}\n\nexport async function fetchMessageReactionsList({\n chat, messageId, reaction, offset,\n}: {\n chat: ApiChat; messageId: number; reaction?: string; offset?: string;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetMessageReactionsList({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageId,\n ...(reaction && { reaction }),\n limit: REACTION_LIST_LIMIT,\n ...(offset && { offset }),\n }));\n\n if (!result) {\n return undefined;\n }\n\n addEntitiesWithPhotosToLocalDb(result.users);\n\n const { nextOffset, reactions, count } = result;\n\n return {\n users: result.users.map(buildApiUser).filter(Boolean as any),\n nextOffset,\n reactions: reactions.map(buildMessagePeerReaction),\n count,\n };\n}\n\nexport function setDefaultReaction({\n reaction,\n}: {\n reaction: string;\n}) {\n return invokeRequest(new GramJs.messages.SetDefaultReaction({\n reaction,\n }));\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChannelStatistics,\n ApiGroupStatistics,\n StatisticsGraph,\n StatisticsOverviewItem,\n StatisticsOverviewPercentage,\n StatisticsOverviewPeriod,\n} from '../../types';\n\nexport function buildChannelStatistics(stats: GramJs.stats.BroadcastStats): ApiChannelStatistics {\n return {\n // Graphs\n growthGraph: buildGraph(stats.growthGraph),\n followersGraph: buildGraph(stats.followersGraph),\n muteGraph: buildGraph(stats.muteGraph),\n topHoursGraph: buildGraph(stats.topHoursGraph),\n\n // Async graphs\n languagesGraph: (stats.languagesGraph as GramJs.StatsGraphAsync).token,\n viewsBySourceGraph: (stats.viewsBySourceGraph as GramJs.StatsGraphAsync).token,\n newFollowersBySourceGraph: (stats.newFollowersBySourceGraph as GramJs.StatsGraphAsync).token,\n interactionsGraph: (stats.interactionsGraph as GramJs.StatsGraphAsync).token,\n\n // Statistics overview\n followers: buildStatisticsOverview(stats.followers),\n viewsPerPost: buildStatisticsOverview(stats.viewsPerPost),\n sharesPerPost: buildStatisticsOverview(stats.sharesPerPost),\n enabledNotifications: buildStatisticsPercentage(stats.enabledNotifications),\n\n // Recent posts\n recentTopMessages: stats.recentMessageInteractions,\n };\n}\n\nexport function buildGroupStatistics(stats: GramJs.stats.MegagroupStats): ApiGroupStatistics {\n return {\n // Graphs\n growthGraph: buildGraph(stats.growthGraph),\n membersGraph: buildGraph(stats.membersGraph),\n topHoursGraph: buildGraph(stats.topHoursGraph),\n\n // Async graphs\n languagesGraph: (stats.languagesGraph as GramJs.StatsGraphAsync).token,\n messagesGraph: (stats.messagesGraph as GramJs.StatsGraphAsync).token,\n actionsGraph: (stats.actionsGraph as GramJs.StatsGraphAsync).token,\n\n // Statistics overview\n period: getOverviewPeriod(stats.period),\n members: buildStatisticsOverview(stats.members),\n viewers: buildStatisticsOverview(stats.viewers),\n messages: buildStatisticsOverview(stats.messages),\n posters: buildStatisticsOverview(stats.posters),\n };\n}\n\nexport function buildGraph(result: GramJs.TypeStatsGraph, isPercentage?: boolean): StatisticsGraph {\n if ((result as GramJs.StatsGraphError).error) {\n throw new Error((result as GramJs.StatsGraphError).error);\n }\n\n const data = JSON.parse((result as GramJs.StatsGraph).json.data);\n const [x, ...y] = data.columns;\n const hasSecondYAxis = data.y_scaled;\n\n return {\n type: isPercentage ? 'area' : data.types.y0,\n zoomToken: (result as GramJs.StatsGraph).zoomToken,\n labelFormatter: data.xTickFormatter,\n tooltipFormatter: data.xTooltipFormatter,\n labels: x.slice(1),\n hideCaption: !data.subchart.show,\n hasSecondYAxis,\n isStacked: data.stacked && !hasSecondYAxis,\n isPercentage,\n datasets: y.map((item: any) => {\n const key = item[0];\n\n return {\n name: data.names[key],\n color: extractColor(data.colors[key]),\n values: item.slice(1),\n };\n }),\n ...calculateMinimapRange(data.subchart.defaultZoom, x.slice(1)),\n };\n}\n\nfunction extractColor(color: string): string {\n return color.substring(color.indexOf('#'));\n}\n\nfunction calculateMinimapRange(range: Array, values: Array) {\n const [min, max] = range;\n\n let minIndex = 0;\n let maxIndex = values.length - 1;\n\n values.forEach((item, index) => {\n if (!minIndex && item >= min) {\n minIndex = index;\n }\n\n if (!maxIndex && item >= max) {\n maxIndex = index;\n }\n });\n\n const begin = Math.max(0, minIndex / (values.length - 1));\n const end = Math.min(1, maxIndex / (values.length - 1));\n\n return { minimapRange: { begin, end }, labelFromIndex: minIndex, labelToIndex: maxIndex };\n}\n\nfunction buildStatisticsOverview({ current, previous }: GramJs.StatsAbsValueAndPrev): StatisticsOverviewItem {\n const change = current - previous;\n\n return {\n current,\n change,\n ...(previous && { percentage: (change ? ((Math.abs(change) / previous) * 100) : 0).toFixed(2) }),\n };\n}\n\nfunction buildStatisticsPercentage(data: GramJs.StatsPercentValue): StatisticsOverviewPercentage {\n return {\n percentage: ((data.part / data.total) * 100).toFixed(2),\n };\n}\n\nfunction getOverviewPeriod(data: GramJs.StatsDateRangeDays): StatisticsOverviewPeriod {\n return {\n maxDate: data.maxDate,\n minDate: data.minDate,\n };\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport {\n ApiChat, ApiChannelStatistics, ApiGroupStatistics, StatisticsGraph,\n} from '../../types';\n\nimport { invokeRequest } from './client';\nimport { buildInputEntity } from '../gramjsBuilders';\nimport { buildChannelStatistics, buildGroupStatistics, buildGraph } from '../apiBuilders/statistics';\n\nexport async function fetchChannelStatistics({\n chat,\n}: { chat: ApiChat }): Promise {\n const result = await invokeRequest(new GramJs.stats.GetBroadcastStats({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n }), undefined, undefined, undefined, chat.fullInfo!.statisticsDcId);\n\n if (!result) {\n return undefined;\n }\n\n return buildChannelStatistics(result);\n}\n\nexport async function fetchGroupStatistics({\n chat,\n}: { chat: ApiChat }): Promise {\n const result = await invokeRequest(new GramJs.stats.GetMegagroupStats({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n }), undefined, undefined, undefined, chat.fullInfo!.statisticsDcId);\n\n if (!result) {\n return undefined;\n }\n\n return buildGroupStatistics(result);\n}\n\nexport async function fetchStatisticsAsyncGraph({\n token,\n x,\n isPercentage,\n dcId,\n}: {\n token: string;\n x?: number;\n isPercentage?: boolean;\n dcId?: number;\n}): Promise {\n const result = await invokeRequest(new GramJs.stats.LoadAsyncGraph({\n token,\n ...(x && { x: BigInt(x) }),\n }), undefined, undefined, undefined, dcId);\n\n if (!result) {\n return undefined;\n }\n\n return buildGraph(result as GramJs.StatsGraph, isPercentage);\n}\n","import {\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 { init as initPayments } from './methods/payments';\nimport * as methods from './methods';\n\nlet onUpdate: OnApiUpdate;\n\nexport async function initApi(_onUpdate: OnApiUpdate, initialArgs: ApiInitialArgs) {\n onUpdate = _onUpdate;\n\n initUpdater(handleUpdate);\n initAuth(handleUpdate);\n initChats(handleUpdate);\n initMessages(handleUpdate);\n initUsers(handleUpdate);\n initStickers(handleUpdate);\n initManagement(handleUpdate);\n initTwoFaSettings(handleUpdate);\n initCalls(handleUpdate);\n initPayments(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\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\n if (DEBUG && typeof response === 'object' && 'CONSTRUCTOR_ID' in response) {\n // eslint-disable-next-line no-console\n console.error(`[GramJs/worker] \\`${name}\\`: Unexpected response \\`${(response as any).className}\\``);\n }\n\n const { arrayBuffer } = (typeof response === 'object' && 'arrayBuffer' in response && response) || {};\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n response,\n }, arrayBuffer);\n }\n } catch (error: any) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n cancelApiProgress(callback);\n }\n\n break;\n }\n case 'ping': {\n sendToOrigin({\n type: 'methodResponse',\n messageId: data.messageId!,\n });\n\n break;\n }\n }\n};\n\nfunction handleErrors() {\n self.onerror = (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.error.message || 'Uncaught exception in worker' } });\n };\n\n self.addEventListener('unhandledrejection', (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.reason.message || 'Uncaught rejection in worker' } });\n });\n}\n\nfunction onUpdate(update: ApiUpdate) {\n sendToOrigin({\n type: 'update',\n update,\n });\n}\n\nfunction sendToOrigin(data: WorkerMessageData, arrayBuffer?: ArrayBuffer) {\n if (arrayBuffer) {\n postMessage(data, [arrayBuffer]);\n } else {\n postMessage(data);\n }\n}\n","const BigInt = require('big-integer');\nconst crypto = require('./crypto/crypto');\n\n/**\n * converts a buffer to big int\n * @param buffer\n * @param little\n * @param signed\n * @returns {bigInt.BigInteger}\n */\nfunction readBigIntFromBuffer(buffer, little = true, signed = false) {\n let randBuffer = Buffer.from(buffer);\n const bytesNumber = randBuffer.length;\n if (little) {\n randBuffer = randBuffer.reverse();\n }\n let bigInt = BigInt(randBuffer.toString('hex'), 16);\n if (signed && Math.floor(bigInt.toString('2').length / 8) >= bytesNumber) {\n bigInt = bigInt.subtract(BigInt(2)\n .pow(BigInt(bytesNumber * 8)));\n }\n return bigInt;\n}\n\n/**\n * Special case signed little ints\n * @param big\n * @param number\n * @returns {Buffer}\n */\nfunction toSignedLittleBuffer(big, number = 8) {\n const bigNumber = BigInt(big);\n const byteArray = [];\n for (let i = 0; i < number; i++) {\n byteArray[i] = bigNumber.shiftRight(8 * i)\n .and(255);\n }\n return Buffer.from(byteArray);\n}\n\n\n/**\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 (Boolean(item) &&\n typeof item === 'object' &&\n typeof (item.length) === 'number' &&\n (item.length === 0 ||\n (item.length > 0 &&\n (item.length - 1) in item)\n )\n )\n )\n}\n*/\n/**\n * Returns the appropriate DC based on the id\n * @param dcId the id of the DC.\n * @param downloadDC whether to use -1 DCs or not\n * (These only support downloading/uploading and not creating a new AUTH key)\n * @return {{port: number, ipAddress: string, id: number}}\n */\nfunction getDC(dcId, downloadDC = false) {\n // TODO Move to external config\n switch (dcId) {\n case 1:\n return {\n id: 1,\n ipAddress: `zws1${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 2:\n return {\n id: 2,\n ipAddress: `zws2${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 3:\n return {\n id: 3,\n ipAddress: `zws3${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 4:\n return {\n id: 4,\n ipAddress: `zws4${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 5:\n return {\n id: 5,\n ipAddress: `zws5${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n default:\n throw new Error(`Cannot find the DC with the ID of ${dcId}`);\n }\n // TODO chose based on current connection method\n /*\n if (!this._config) {\n this._config = await this.invoke(new requests.help.GetConfig())\n }\n if (cdn && !this._cdnConfig) {\n this._cdnConfig = await this.invoke(new requests.help.GetCdnConfig())\n for (const pk of this._cdnConfig.publicKeys) {\n addKey(pk.publicKey)\n }\n }\n for (const DC of this._config.dcOptions) {\n if (DC.id === dcId && Boolean(DC.ipv6) === this._useIPV6 && Boolean(DC.cdn) === cdn) {\n return DC\n }\n } */\n}\n\nmodule.exports = {\n getMessageId,\n // _getEntityPair,\n // getInputMessage,\n // getInputDialog,\n // getInputUser,\n // getInputChannel,\n getInputPeer,\n // parsePhone,\n // parseUsername,\n // getPeer,\n // getPeerId,\n getDisplayName,\n // resolveId,\n // isListLike,\n 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: any) {\n onEmailCodeError!(err);\n }\n }\n } else {\n throw e;\n }\n }\n}\n","const os = require('os');\nconst Logger = require('../extensions/Logger');\nconst { sleep } = require('../Helpers');\nconst errors = require('../errors');\nconst MemorySession = require('../sessions/Memory');\nconst Helpers = require('../Helpers');\nconst utils = require('../Utils');\nconst Session = require('../sessions/Abstract');\nconst { LAYER } = require('../tl/AllTLObjects');\nconst {\n constructors,\n requests,\n} = require('../tl');\nconst {\n ConnectionTCPObfuscated,\n MTProtoSender,\n UpdateConnectionState,\n} = require('../network');\nconst {\n authFlow,\n checkAuthorization,\n} = require('./auth');\nconst { downloadFile } = require('./downloadFile');\nconst { uploadFile } = require('./uploadFile');\nconst { updateTwoFaSettings } = require('./2fa');\n\nconst DEFAULT_DC_ID = 2;\nconst WEBDOCUMENT_DC_ID = 4;\nconst DEFAULT_IPV4_IP = 'zws2.web.telegram.org';\nconst DEFAULT_IPV6_IP = '[2001:67c:4e8:f002::a]';\nconst EXPORTED_SENDER_RECONNECT_TIMEOUT = 1000; // 1 sec\nconst EXPORTED_SENDER_RELEASE_TIMEOUT = 30000; // 30 sec\nconst WEBDOCUMENT_REQUEST_PART_SIZE = 131072; // 128kb\n\nconst PING_INTERVAL = 3000; // 3 sec\nconst PING_TIMEOUT = 5000; // 5 sec\nconst PING_FAIL_ATTEMPTS = 3;\nconst PING_FAIL_INTERVAL = 100; // ms\n\n// An unusually long interval is a sign of returning from background mode...\nconst PING_INTERVAL_TO_WAKE_UP = 5000; // 5 sec\n// ... so we send a quick \"wake-up\" ping to confirm than connection was dropped ASAP\nconst PING_WAKE_UP_TIMEOUT = 3000; // 3 sec\n// We also send a warning to the user even a bit more quickly\nconst PING_WAKE_UP_WARNING_TIMEOUT = 1000; // 1 sec\n\nconst PING_DISCONNECT_DELAY = 60000; // 1 min\n\n// All types\nconst sizeTypes = ['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._isSwitchingDc = false;\n this._destroyed = false;\n }\n\n // region Connecting\n\n /**\n * Connects to the Telegram servers, executing authentication if required.\n * Note that authenticating to the Telegram servers is not the same as authenticating\n * the app, which requires to send a code first.\n * @returns {Promise}\n */\n async connect() {\n await this._initSession();\n\n if (this._sender === undefined) {\n // only init sender once to avoid multiple loops.\n this._sender = new MTProtoSender(this.session.getAuthKey(), {\n logger: this._log,\n dcId: this.session.dcId,\n retries: this._connectionRetries,\n delay: this._retryDelay,\n autoReconnect: this._autoReconnect,\n connectTimeout: this._timeout,\n authKeyCallback: this._authKeyCallback.bind(this),\n updateCallback: this._handleUpdate.bind(this),\n isMainSender: true,\n });\n }\n // set defaults vars\n this._sender.userDisconnected = false;\n this._sender._user_connected = false;\n this._sender.isReconnecting = false;\n this._sender._disconnected = true;\n\n const connection = new this._connection(\n this.session.serverAddress, this.session.port, this.session.dcId, this._log, this._args.testServers,\n );\n\n const newConnection = await this._sender.connect(connection);\n if (!newConnection) {\n // we're already connected so no need to reset auth key.\n if (!this._loopStarted) {\n this._updateLoop();\n this._loopStarted = true;\n }\n return;\n }\n\n this.session.setAuthKey(this._sender.authKey);\n await this._sender.send(this._initWith(\n new requests.help.GetConfig({}),\n ));\n\n if (!this._loopStarted) {\n this._updateLoop();\n this._loopStarted = true;\n }\n this._isSwitchingDc = false;\n }\n\n async _initSession() {\n await this.session.load();\n\n if (!this.session.serverAddress || (this.session.serverAddress.includes(':') !== this._useIPV6)) {\n this.session.setDC(DEFAULT_DC_ID, this._useIPV6\n ? DEFAULT_IPV6_IP : DEFAULT_IPV4_IP, this._args.useWSS ? 443 : 80);\n }\n }\n\n async _updateLoop() {\n let lastPongAt;\n\n while (!this._destroyed) {\n await Helpers.sleep(PING_INTERVAL);\n if (this._sender.isReconnecting || this._isSwitchingDc) {\n lastPongAt = undefined;\n continue;\n }\n\n try {\n const ping = () => {\n return this._sender.send(new requests.PingDelayDisconnect({\n pingId: Helpers.getRandomInt(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER),\n disconnectDelay: PING_DISCONNECT_DELAY,\n }));\n };\n\n const pingAt = Date.now();\n const lastInterval = lastPongAt ? pingAt - lastPongAt : undefined;\n\n if (!lastInterval || lastInterval < PING_INTERVAL_TO_WAKE_UP) {\n await attempts(() => timeout(ping, PING_TIMEOUT), PING_FAIL_ATTEMPTS, PING_FAIL_INTERVAL);\n } else {\n let wakeUpWarningTimeout = setTimeout(() => {\n this._handleUpdate(new UpdateConnectionState(UpdateConnectionState.disconnected));\n wakeUpWarningTimeout = undefined;\n }, PING_WAKE_UP_WARNING_TIMEOUT);\n\n await timeout(ping, PING_WAKE_UP_TIMEOUT);\n\n if (wakeUpWarningTimeout) {\n clearTimeout(wakeUpWarningTimeout);\n wakeUpWarningTimeout = undefined;\n }\n\n this._handleUpdate(new UpdateConnectionState(UpdateConnectionState.connected));\n }\n\n lastPongAt = Date.now();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n\n lastPongAt = undefined;\n\n if (this._sender.isReconnecting || this._isSwitchingDc) {\n continue;\n }\n\n await this.disconnect();\n await this.connect();\n }\n\n // We need to send some content-related request at least hourly\n // for Telegram to keep delivering updates, otherwise they will\n // just stop even if we're connected. Do so every 30 minutes.\n\n // TODO Call getDifference instead since it's more relevant\n if (new Date().getTime() - this._lastRequest > 30 * 60 * 1000) {\n try {\n await this.invoke(new requests.updates.GetState());\n } catch (e) {\n // we don't care about errors here\n }\n\n lastPongAt = undefined;\n }\n }\n await this.disconnect();\n }\n\n /**\n * Disconnects from the Telegram server\n * @returns {Promise}\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._isSwitchingDc = true;\n await this.disconnect();\n return this.connect();\n }\n\n _authKeyCallback(authKey, dcId) {\n this.session.setAuthKey(authKey, dcId);\n }\n\n // endregion\n // export region\n\n async _cleanupExportedSender(dcId) {\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, Boolean(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 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 async downloadStaticMap(accessHash, long, lat, w, h, zoom, scale, accuracyRadius) {\n try {\n const buff = [];\n let offset = 0;\n while (true) {\n try {\n const downloaded = new requests.upload.GetWebFile({\n location: new constructors.InputWebFileGeoPointLocation({\n geoPoint: new constructors.InputGeoPoint({\n lat,\n long,\n accuracyRadius,\n }),\n accessHash,\n w,\n h,\n zoom,\n scale,\n }),\n offset,\n limit: WEBDOCUMENT_REQUEST_PART_SIZE,\n });\n const sender = await this._borrowExportedSender(WEBDOCUMENT_DC_ID);\n const res = await sender.send(downloaded);\n offset += 131072;\n if (res.bytes.length) {\n buff.push(res.bytes);\n if (res.bytes.length < WEBDOCUMENT_REQUEST_PART_SIZE) {\n break;\n }\n } else {\n break;\n }\n } catch (err) {\n if (err instanceof errors.FloodWaitError) {\n // eslint-disable-next-line no-console\n console.warn(`getWebFile: sleeping for ${err.seconds}s on flood wait`);\n await sleep(err.seconds * 1000);\n continue;\n }\n }\n }\n return Buffer.concat(buff);\n } catch (e) {\n // the file is no longer saved in telegram's cache.\n if (e.message === 'WEBFILE_NOT_AVAILABLE') {\n return Buffer.alloc(0);\n } else {\n throw e;\n }\n }\n }\n\n // region Invoking Telegram request\n /**\n * Invokes a MTProtoRequest (sends and receives it) and returns its result\n * @param request\n * @param dcId Optional dcId to use when sending the request\n * @returns {Promise}\n */\n\n async invoke(request, dcId) {\n if (request.classType !== 'request') {\n throw new Error('You can only invoke MTProtoRequests');\n }\n\n const sender = dcId === undefined ? this._sender : await this.getSender(dcId);\n this._lastRequest = new Date().getTime();\n let attempt = 0;\n for (attempt = 0; attempt < this._requestRetries; attempt++) {\n const promise = sender.sendWithInvokeSupport(request);\n try {\n const result = await promise.promise;\n return result;\n } catch (e) {\n if (e instanceof errors.ServerError || e.message === 'RPC_CALL_FAIL'\n || e.message === 'RPC_MCGET_FAIL') {\n this._log.warn(`Telegram is having internal issues ${e.constructor.name}`);\n await sleep(2000);\n } else if (e instanceof errors.FloodWaitError || e instanceof errors.FloodTestPhoneWaitError) {\n if (e.seconds <= this.floodSleepLimit) {\n this._log.info(`Sleeping for ${e.seconds}s on flood wait`);\n await sleep(e.seconds * 1000);\n } else {\n throw e;\n }\n } else if (e instanceof errors.PhoneMigrateError || e instanceof errors.NetworkMigrateError\n || e instanceof errors.UserMigrateError) {\n this._log.info(`Phone migrated to ${e.newDc}`);\n const shouldRaise = e instanceof errors.PhoneMigrateError\n || e instanceof errors.NetworkMigrateError;\n if (shouldRaise && await checkAuthorization(this)) {\n throw e;\n }\n await this._switchDC(e.newDc);\n } else if (e instanceof errors.MsgWaitError) {\n // we need to resend this after the old one was confirmed.\n await promise.isReady();\n } else {\n throw e;\n }\n }\n }\n throw new Error(`Request was unsuccessful ${attempt} time(s)`);\n }\n\n 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(cb, ms) {\n return Promise.race([\n cb(),\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 @typescript-eslint/return-await\n return await cb();\n } catch (err) {\n if (i === times - 1) {\n throw err;\n }\n\n await Helpers.sleep(pause);\n }\n }\n return undefined;\n}\n\nmodule.exports = TelegramClient;\n","// 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: any) {\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: any) {\n if (err.message === 'RESTART_AUTH_WITH_QR') {\n return signInUserWithQrCode(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n } else {\n phoneNumber = authParams.phoneNumber;\n }\n const sendCodeResult = await sendCode(client, apiCredentials, phoneNumber, authParams.forceSMS);\n phoneCodeHash = sendCodeResult.phoneCodeHash;\n isCodeViaApp = sendCodeResult.isCodeViaApp;\n\n if (typeof phoneCodeHash !== 'string') {\n throw new Error('Failed to retrieve phone code hash');\n }\n\n break;\n } catch (err: any) {\n if (typeof authParams.phoneNumber !== 'function') {\n throw err;\n }\n\n authParams.onError(err);\n }\n }\n\n let phoneCode;\n let isRegistrationRequired = false;\n let termsOfService;\n\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n try {\n phoneCode = await authParams.phoneCode(isCodeViaApp);\n } catch (err: any) {\n // This is the support for changing phone number from the phone code screen.\n if (err.message === 'RESTART_AUTH') {\n return signInUser(client, apiCredentials, authParams);\n }\n }\n\n if (!phoneCode) {\n throw new Error('Code is empty');\n }\n\n // May raise PhoneCodeEmptyError, PhoneCodeExpiredError,\n // PhoneCodeHashEmptyError or PhoneCodeInvalidError.\n const result = await client.invoke(new Api.auth.SignIn({\n phoneNumber,\n phoneCodeHash,\n phoneCode,\n }));\n\n if (result instanceof Api.auth.AuthorizationSignUpRequired) {\n isRegistrationRequired = true;\n termsOfService = result.termsOfService;\n break;\n }\n\n return result.user;\n } catch (err: any) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n } else {\n authParams.onError(err);\n }\n }\n }\n\n if (isRegistrationRequired) {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const [firstName, lastName] = await authParams.firstAndLastNames();\n if (!firstName) {\n throw new Error('First name is required');\n }\n\n const { user } = await client.invoke(new Api.auth.SignUp({\n phoneNumber,\n phoneCodeHash,\n firstName,\n lastName,\n })) as Api.auth.Authorization;\n\n if (termsOfService) {\n // This is a violation of Telegram rules: the user should be presented with and accept TOS.\n await client.invoke(new Api.help.AcceptTermsOfService({ id: termsOfService.id }));\n }\n\n return user;\n } catch (err: any) {\n authParams.onError(err);\n }\n }\n }\n\n authParams.onError(new Error('Auth failed'));\n return signInUser(client, apiCredentials, authParams);\n}\n\nasync function signInUserWithQrCode(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\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: any) {\n if (err.message === 'RESTART_AUTH') {\n return await signInUser(client, apiCredentials, authParams);\n }\n\n throw err;\n } finally {\n isScanningComplete = true;\n }\n\n try {\n const result2 = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n\n if (result2 instanceof Api.auth.LoginTokenSuccess && result2.authorization instanceof Api.auth.Authorization) {\n return result2.authorization.user;\n } else if (result2 instanceof Api.auth.LoginTokenMigrateTo) {\n await client._switchDC(result2.dcId);\n const migratedResult = await client.invoke(new Api.auth.ImportLoginToken({\n token: result2.token,\n }));\n\n if (migratedResult instanceof Api.auth.LoginTokenSuccess\n && migratedResult.authorization instanceof Api.auth.Authorization) {\n return migratedResult.authorization.user;\n }\n }\n } catch (err: any) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n\n // This is a workaround for TypeScript (never actually reached)\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw undefined;\n}\n\nasync function sendCode(\n client: TelegramClient, apiCredentials: ApiCredentials, phoneNumber: string, forceSMS = false,\n): Promise<{\n phoneCodeHash: string;\n isCodeViaApp: boolean;\n }> {\n try {\n const { apiId, apiHash } = apiCredentials;\n const sendResult = await client.invoke(new Api.auth.SendCode({\n phoneNumber,\n apiId,\n apiHash,\n settings: new Api.CodeSettings(),\n }));\n\n // If we already sent a SMS, do not resend the phoneCode (hash may be empty)\n if (!forceSMS || (sendResult.type instanceof Api.auth.SentCodeTypeSms)) {\n return {\n phoneCodeHash: sendResult.phoneCodeHash,\n isCodeViaApp: sendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n }\n\n const resendResult = await client.invoke(new Api.auth.ResendCode({\n phoneNumber,\n phoneCodeHash: sendResult.phoneCodeHash,\n }));\n\n return {\n phoneCodeHash: resendResult.phoneCodeHash,\n isCodeViaApp: resendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n } catch (err: any) {\n if (err.message === 'AUTH_RESTART') {\n return sendCode(client, apiCredentials, phoneNumber, forceSMS);\n } else {\n throw err;\n }\n }\n}\n\nasync function signInWithPassword(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const passwordSrpResult = await client.invoke(new Api.account.GetPassword());\n const password = await authParams.password(passwordSrpResult.hint);\n if (!password) {\n throw new Error('Password is empty');\n }\n\n const passwordSrpCheck = await computePasswordSrpCheck(passwordSrpResult, password);\n const { user } = await client.invoke(new Api.auth.CheckPassword({\n password: passwordSrpCheck,\n })) as Api.auth.Authorization;\n\n return user;\n } catch (err: any) {\n authParams.onError(err);\n }\n }\n\n // eslint-disable-next-line no-unreachable\n return undefined!; // Never reached (TypeScript fix)\n}\n\nasync function signInBot(client: TelegramClient, apiCredentials: ApiCredentials, authParams: BotAuthParams) {\n const { apiId, apiHash } = apiCredentials;\n const { botAuthToken } = authParams;\n\n const { user } = await client.invoke(new Api.auth.ImportBotAuthorization({\n apiId,\n apiHash,\n botAuthToken,\n })) as Api.auth.Authorization;\n\n return user;\n}\n","// 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('./updates');\nconst { BadMessageError } = require('../errors/Common');\nconst {\n BadServerSalt,\n BadMsgNotification,\n MsgDetailedInfo,\n MsgNewDetailedInfo,\n NewSessionCreated,\n FutureSalts,\n MsgsStateReq,\n MsgResendReq,\n MsgsAllInfo,\n} = require('../tl').constructors;\nconst { SecurityError } = require('../errors/Common');\nconst { InvalidBufferError } = require('../errors/Common');\nconst { LogOut } = require('../tl').requests.auth;\nconst { RPCMessageToError } = require('../errors');\nconst { TypeNotFoundError } = require('../errors/Common');\n\n/**\n * MTProto Mobile Protocol sender\n * (https://core.telegram.org/mtproto/description)\n * This class is responsible for wrapping requests into `TLMessage`'s,\n * sending them over the network and receiving them in a safe manner.\n *\n * Automatic reconnection due to temporary network issues is a concern\n * for this class as well, including retry of messages that could not\n * be sent successfully.\n *\n * A new authorization key will be generated on connection if no other\n * key exists yet.\n */\nclass MTProtoSender {\n static DEFAULT_OPTIONS = {\n logger: undefined,\n retries: Infinity,\n delay: 2000,\n autoReconnect: true,\n connectTimeout: undefined,\n authKeyCallback: undefined,\n updateCallback: undefined,\n autoReconnectCallback: undefined,\n isMainSender: undefined,\n onConnectionBreak: undefined,\n };\n\n /**\n * @param authKey\n * @param opts\n */\n constructor(authKey, opts) {\n const args = { ...MTProtoSender.DEFAULT_OPTIONS, ...opts };\n this._connection = undefined;\n this._log = args.logger;\n this._dcId = args.dcId;\n this._retries = args.retries;\n this._delay = args.delay;\n this._autoReconnect = args.autoReconnect;\n this._connectTimeout = args.connectTimeout;\n this._authKeyCallback = args.authKeyCallback;\n this._updateCallback = args.updateCallback;\n this._autoReconnectCallback = args.autoReconnectCallback;\n this._isMainSender = args.isMainSender;\n this._onConnectionBreak = args.onConnectionBreak;\n\n /**\n * whether we disconnected ourself or telegram did it.\n */\n this.userDisconnected = false;\n\n /**\n * Whether the user has explicitly connected or disconnected.\n *\n * If a disconnection happens for any other reason and it\n * was *not* user action then the pending messages won't\n * be cleared but on explicit user disconnection all the\n * pending futures should be cancelled.\n */\n this._user_connected = false;\n this.isReconnecting = false;\n this._disconnected = true;\n\n /**\n * We need to join the loops upon disconnection\n */\n this._send_loop_handle = undefined;\n this._recv_loop_handle = undefined;\n\n /**\n * Preserving the references of the AuthKey and state is important\n */\n this.authKey = authKey || new AuthKey();\n this._state = new MTProtoState(this.authKey, this._log);\n\n /**\n * Outgoing messages are put in a queue and sent in a batch.\n * Note that here we're also storing their ``_RequestState``.\n */\n this._send_queue = new MessagePacker(this._state, this._log);\n\n /**\n * Sent states are remembered until a response is received.\n */\n this._pending_state = {};\n\n /**\n * Responses must be acknowledged, and we can also batch these.\n */\n this._pending_ack = new Set();\n\n /**\n * Similar to pending_messages but only for the last acknowledges.\n * These can't go in pending_messages because no acknowledge for them\n * is received, but we may still need to resend their state on bad salts.\n */\n this._last_acks = [];\n\n /**\n * Jump table from response ID to method that handles it\n */\n\n this._handlers = {\n [RPCResult.CONSTRUCTOR_ID]: this._handleRPCResult.bind(this),\n [MessageContainer.CONSTRUCTOR_ID]: this._handleContainer.bind(this),\n [GZIPPacked.CONSTRUCTOR_ID]: this._handleGzipPacked.bind(this),\n [Pong.CONSTRUCTOR_ID]: this._handlePong.bind(this),\n [BadServerSalt.CONSTRUCTOR_ID]: this._handleBadServerSalt.bind(this),\n [BadMsgNotification.CONSTRUCTOR_ID]: this._handleBadNotification.bind(this),\n [MsgDetailedInfo.CONSTRUCTOR_ID]: this._handleDetailedInfo.bind(this),\n [MsgNewDetailedInfo.CONSTRUCTOR_ID]: this._handleNewDetailedInfo.bind(this),\n [NewSessionCreated.CONSTRUCTOR_ID]: this._handleNewSessionCreated.bind(this),\n [MsgsAck.CONSTRUCTOR_ID]: this._handleAck.bind(this),\n [FutureSalts.CONSTRUCTOR_ID]: this._handleFutureSalts.bind(this),\n [MsgsStateReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgResendReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgsAllInfo.CONSTRUCTOR_ID]: this._handleMsgAll.bind(this),\n };\n }\n\n // Public API\n\n /**\n * Connects to the specified given connection using the given auth key.\n * @param connection\n * @param [force]\n * @returns {Promise}\n */\n async connect(connection, force) {\n this.userDisconnected = false;\n\n if (this._user_connected && !force) {\n this._log.info('User is already connected!');\n return false;\n }\n this.isConnecting = true;\n this._connection = connection;\n\n for (let attempt = 0; attempt < this._retries; attempt++) {\n try {\n await this._connect();\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.connected));\n }\n break;\n } catch (err) {\n if (this._updateCallback && attempt === 0) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n this._log.error(`WebSocket connection failed attempt: ${attempt + 1}`);\n // eslint-disable-next-line no-console\n console.error(err);\n await Helpers.sleep(this._delay);\n }\n }\n this.isConnecting = false;\n return true;\n }\n\n isConnected() {\n return this._user_connected;\n }\n\n /**\n * Cleanly disconnects the instance from the network, cancels\n * all pending requests, and closes the send and receive loops.\n */\n async disconnect() {\n this.userDisconnected = true;\n await this._disconnect();\n }\n\n /**\n *\n This method enqueues the given request to be sent. Its send\n state will be saved until a response arrives, and a ``Future``\n that will be resolved when the response arrives will be returned:\n\n .. code-block:: javascript\n\n async def method():\n # Sending (enqueued for the send loop)\n future = sender.send(request)\n # Receiving (waits for the receive loop to read the result)\n result = await future\n\n Designed like this because Telegram may send the response at\n any point, and it can send other items while one waits for it.\n Once the response for this future arrives, it is set with the\n received result, quite similar to how a ``receive()`` call\n would otherwise work.\n\n Since the receiving part is \"built in\" the future, it's\n impossible to await receive a result that was never sent.\n * @param request\n * @returns {RequestState}\n */\n send(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected');\n }\n const state = new RequestState(request);\n this._send_queue.append(state);\n return state.promise;\n }\n\n /**\n * Same as send but returns the full state. usefull for invoke after logic\n * @param request\n * @return {RequestState}\n */\n sendWithInvokeSupport(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected');\n }\n const state = new RequestState(request, undefined, this._pending_state);\n this._send_queue.append(state);\n return state;\n }\n\n /**\n * Performs the actual connection, retrying, generating the\n * authorization key if necessary, and starting the send and\n * receive loops.\n * @returns {Promise}\n * @private\n */\n async _connect() {\n this._log.info('Connecting to {0}...'.replace('{0}', this._connection));\n await this._connection.connect();\n this._log.debug('Connection success!');\n // process.exit(0)\n if (!this.authKey.getKey()) {\n const plain = new MtProtoPlainSender(this._connection, this._log);\n this._log.debug('New auth_key attempt ...');\n const res = await doAuthentication(plain, this._log);\n this._log.debug('Generated new auth_key successfully');\n await this.authKey.setKey(res.authKey);\n\n this._state.timeOffset = res.timeOffset;\n\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(this._state.timeOffset));\n }\n\n /**\n * This is *EXTREMELY* important since we don't control\n * external references to the authorization key, we must\n * notify whenever we change it. This is crucial when we\n * switch to different data centers.\n */\n if (this._authKeyCallback) {\n await this._authKeyCallback(this.authKey, this._dcId);\n }\n } else {\n this._authenticated = true;\n this._log.debug('Already have an auth key ...');\n }\n this._user_connected = true;\n this.isReconnecting = false;\n\n this._log.debug('Starting send loop');\n this._send_loop_handle = this._sendLoop();\n\n this._log.debug('Starting receive loop');\n this._recv_loop_handle = this._recvLoop();\n\n // _disconnected only completes after manual disconnection\n // or errors after which the sender cannot continue such\n // as failing to reconnect or any unexpected error.\n\n this._log.info('Connection to %s complete!'.replace('%s', this._connection.toString()));\n }\n\n async _disconnect() {\n this._send_queue.rejectAll();\n\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n\n if (this._connection === undefined) {\n this._log.info('Not disconnecting (already have no connection)');\n return;\n }\n\n this._log.info('Disconnecting from %s...'.replace('%s', this._connection.toString()));\n this._user_connected = false;\n this._log.debug('Closing current connection...');\n await this._connection.disconnect();\n }\n\n /**\n * This loop is responsible for popping items off the send\n * queue, encrypting them, and sending them over the network.\n * Besides `connect`, only this method ever sends data.\n * @returns {Promise}\n * @private\n */\n async _sendLoop() {\n this._send_queue = new MessagePacker(this._state, this._log);\n\n while (this._user_connected && !this.isReconnecting) {\n if (this._pending_ack.size) {\n const ack = new RequestState(new MsgsAck({ msgIds: Array(...this._pending_ack) }));\n this._send_queue.append(ack);\n this._last_acks.push(ack);\n if (this._last_acks.length >= 10) {\n this._last_acks.shift();\n }\n this._pending_ack.clear();\n }\n this._log.debug(`Waiting for messages to send...${this.isReconnecting}`);\n // TODO Wait for the connection send queue to be empty?\n // This means that while it's not empty we can wait for\n // more messages to be added to the send queue.\n const res = await this._send_queue.get();\n\n if (this.isReconnecting) {\n return;\n }\n\n if (!res) {\n continue;\n }\n let { data } = res;\n const { batch } = res;\n this._log.debug(`Encrypting ${batch.length} message(s) in ${data.length} bytes for sending`);\n\n data = await this._state.encryptMessageData(data);\n\n try {\n await this._connection.send(data);\n } catch (e) {\n this._log.error(e);\n this._log.info('Connection closed while sending data');\n return;\n }\n for (const state of batch) {\n if (!Array.isArray(state)) {\n if (state.request.classType === 'request') {\n this._pending_state[state.msgId] = state;\n }\n } else {\n for (const s of state) {\n if (s.request.classType === 'request') {\n this._pending_state[s.msgId] = s;\n }\n }\n }\n }\n this._log.debug('Encrypted messages put in a queue to be sent');\n }\n }\n\n async _recvLoop() {\n let body;\n let message;\n\n while (this._user_connected && !this.isReconnecting) {\n // this._log.debug('Receiving items from the network...');\n this._log.debug('Receiving items from the network...');\n try {\n body = await this._connection.recv();\n } catch (e) {\n // this._log.info('Connection closed while receiving data');\n /** when the server disconnects us we want to reconnect */\n if (!this.userDisconnected) {\n this._log.error(e);\n this._log.warn('Connection closed while receiving data');\n this.reconnect();\n }\n return;\n }\n try {\n message = await this._state.decryptMessageData(body);\n } catch (e) {\n if (e instanceof TypeNotFoundError) {\n // Received object which we don't know how to deserialize\n this._log.info(`Type ${e.invalidConstructorId} not found, remaining data ${e.remaining}`);\n continue;\n } else if (e instanceof SecurityError) {\n // A step while decoding had the incorrect data. This message\n // should not be considered safe and it should be ignored.\n this._log.warn(`Security error while unpacking a received message: ${e}`);\n continue;\n } else if (e instanceof InvalidBufferError) {\n // 404 means that the server has \"forgotten\" our auth key and we need to create a new one.\n if (e.code === 404) {\n this._handleBadAuthKey();\n } else {\n // this happens sometimes when telegram is having some internal issues.\n // reconnecting should be enough usually\n // since the data we sent and received is probably wrong now.\n this._log.warn(`Invalid buffer ${e.code} for dc ${this._dcId}`);\n this.reconnect();\n }\n return;\n } else {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n this.reconnect();\n return;\n }\n }\n try {\n await this._processMessage(message);\n } catch (e) {\n // `RPCError` errors except for 'AUTH_KEY_UNREGISTERED' should be handled by the client\n if (e instanceof RPCError) {\n if (e.message === 'AUTH_KEY_UNREGISTERED') {\n // 'AUTH_KEY_UNREGISTERED' for the main sender is thrown when unauthorized and should be ignored\n this._handleBadAuthKey(true);\n }\n } else {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n }\n }\n }\n }\n\n _handleBadAuthKey(shouldSkipForMain) {\n if (shouldSkipForMain && this._isMainSender) {\n return;\n }\n\n this._log.warn(`Broken authorization key for dc ${this._dcId}, resetting...`);\n\n if (this._isMainSender && this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.broken));\n } else if (!this._isMainSender && this._onConnectionBreak) {\n this._onConnectionBreak(this._dcId);\n }\n }\n\n // Response Handlers\n\n /**\n * Adds the given message to the list of messages that must be\n * acknowledged and dispatches control to different ``_handle_*``\n * method based on its type.\n * @param message\n * @returns {Promise}\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.isReconnecting) {\n this.isReconnecting = true;\n // TODO Should we set this?\n // this._user_connected = false\n // we want to wait a second between each reconnect try to not flood the server with reconnects\n // in case of internal server issues.\n Helpers.sleep(1000)\n .then(() => {\n this._log.info('Started reconnecting');\n this._reconnect();\n });\n }\n }\n\n async _reconnect() {\n this._log.debug('Closing current connection...');\n try {\n await this._disconnect();\n } catch (err) {\n this._log.warn(err);\n }\n\n this._send_queue.append(undefined);\n this._state.reset();\n\n // For some reason reusing existing connection caused stuck requests\n const newConnection = new this._connection.constructor(\n this._connection._ip,\n this._connection._port,\n this._connection._dcId,\n this._connection._log,\n this._connection._testServers,\n );\n await this.connect(newConnection, true);\n\n this.isReconnecting = false;\n // uncomment this if you want to resend\n // this._send_queue.extend(Object.values(this._pending_state))\n for (const state of Object.values(this._pending_state)) {\n state.deferred.resolve();\n }\n this._pending_state = {};\n if (this._autoReconnectCallback) {\n await this._autoReconnectCallback();\n }\n }\n}\n\nmodule.exports = MTProtoSender;\n","const BigInt = require('big-integer');\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\nconst {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n} = require('./connection');\n\nconst {\n UpdateConnectionState,\n UpdateServerTimeOffset,\n} = require('./updates');\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n MTProtoPlainSender,\n MTProtoSender,\n UpdateConnectionState,\n UpdateServerTimeOffset,\n};\n","class UpdateConnectionState {\n static disconnected = -1;\n\n static connected = 1;\n\n static broken = 0;\n\n constructor(state, origin) {\n this.state = state;\n this.origin = origin;\n }\n}\n\nclass UpdateServerTimeOffset {\n constructor(timeOffset) {\n this.timeOffset = timeOffset;\n }\n}\n\nmodule.exports = {\n UpdateConnectionState,\n UpdateServerTimeOffset,\n};\n","class Session {\n /**\n * Creates a clone of this session file\n * @param toInstance {Session|null}\n * @returns {Session}\n */\n\n /* CONTEST\n clone(toInstance = null) {\n return toInstance || new this.constructor()\n } */\n\n /**\n * Returns the currently-used data center ID.\n */\n get dcId() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns the server address where the library should connect to.\n */\n get serverAddress() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns the port to which the library should connect to.\n */\n get port() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns an ``AuthKey`` instance associated with the saved\n * data center, or `None` if a new one should be generated.\n */\n get authKey() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Sets the ``AuthKey`` to be used for the saved data center.\n * @param value\n */\n set authKey(value) {\n throw new Error('Not Implemented');\n }\n\n /**\n * Sets the information of the data center address and port that\n * the library should connect to, as well as the data center ID,\n * which is currently unused.\n * @param dcId {number}\n * @param serverAddress {string}\n * @param port {number}\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setDC(dcId, serverAddress, port) {\n throw new Error('Not implemented');\n }\n\n /**\n * Returns an ID of the takeout process initialized for this session,\n * or `None` if there's no were any unfinished takeout requests.\n */\n /* CONTEST\n get takeoutId() {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Sets the ID of the unfinished takeout process for this session.\n * @param value\n */\n /* CONTEST\n set takeoutId(value) {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Returns the ``UpdateState`` associated with the given `entity_id`.\n * If the `entity_id` is 0, it should return the ``UpdateState`` for\n * no specific channel (the \"general\" state). If no state is known\n * it should ``return None``.\n * @param entityId\n */\n /* CONTEST\n getUpdateState(entityId) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Sets the given ``UpdateState`` for the specified `entity_id`, which\n * should be 0 if the ``UpdateState`` is the \"general\" state (and not\n * for any specific channel).\n * @param entityId\n * @param state\n */\n /* CONTEST\n setUpdateState(entityId, state) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Called on client disconnection. Should be used to\n * free any used resources. Can be left empty if none.\n */\n\n /* CONTEST\n close() {\n\n }\n\n */\n\n /**\n * called whenever important properties change. It should\n * make persist the relevant session information to disk.\n */\n save() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Called upon client.log_out(). Should delete the stored\n * information from disk since it's not valid anymore.\n */\n\n delete() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Lists available sessions. Not used by the library itself.\n */\n /* CONTEST\n listSessions() {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Processes the input ``TLObject`` or ``list`` and saves\n * whatever information is relevant (e.g., ID or access hash).\n * @param tlo\n */\n /* CONTEST\n processEntities(tlo) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Turns the given key into an ``InputPeer`` (e.g. ``InputPeerUser``).\n * The library uses this method whenever an ``InputPeer`` is needed\n * to suit several purposes (e.g. user only provided its ID or wishes\n * to use a cached username to avoid extra RPC).\n */\n /* CONTEST\n getInputEntity(key) {\n throw new Error('Not Implemented')\n }\n\n */\n}\n\nmodule.exports = Session;\n","/* eslint-disable no-restricted-globals */\nconst StorageSession = require('./StorageSession');\n\nconst CACHE_NAME = 'GramJs';\n\nclass CacheApiSession extends StorageSession {\n async _delete() {\n const request = new Request(this._storageKey);\n const cache = await self.caches.open(CACHE_NAME);\n return cache.delete(request);\n }\n\n async _fetchFromCache() {\n const request = new Request(this._storageKey);\n const cache = await self.caches.open(CACHE_NAME);\n const cached = await cache.match(request);\n return cached ? cached.text() : undefined;\n }\n\n async _saveToCache(data) {\n const request = new Request(this._storageKey);\n const response = new Response(data);\n const cache = await self.caches.open(CACHE_NAME);\n return cache.put(request, response);\n }\n}\n\nmodule.exports = CacheApiSession;\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst utils = require('../Utils');\n\nclass CallbackSession extends MemorySession {\n constructor(sessionData, callback) {\n super();\n\n this._sessionData = sessionData;\n this._callback = callback;\n\n this._authKeys = {};\n }\n\n get authKey() {\n throw new Error('Not supported');\n }\n\n set authKey(value) {\n throw new Error('Not supported');\n }\n\n async load() {\n if (!this._sessionData) {\n return;\n }\n\n const {\n mainDcId,\n keys,\n hashes,\n } = this._sessionData;\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n\n this.setDC(mainDcId, ipAddress, port, true);\n\n await Promise.all(Object.keys(keys)\n .map(async (dcId) => {\n const key = typeof keys[dcId] === 'string'\n ? Buffer.from(keys[dcId], 'hex')\n : Buffer.from(keys[dcId]);\n\n if (hashes[dcId]) {\n const hash = typeof hashes[dcId] === 'string'\n ? Buffer.from(hashes[dcId], 'hex')\n : Buffer.from(hashes[dcId]);\n\n this._authKeys[dcId] = new AuthKey(key, hash);\n } else {\n this._authKeys[dcId] = new AuthKey();\n await this._authKeys[dcId].setKey(key, true);\n }\n }));\n }\n\n setDC(dcId, serverAddress, port, skipOnUpdate = false) {\n this._dcId = dcId;\n this._serverAddress = serverAddress;\n this._port = port;\n\n delete this._authKeys[dcId];\n\n if (!skipOnUpdate) {\n void this._onUpdate();\n }\n }\n\n getAuthKey(dcId = this._dcId) {\n return this._authKeys[dcId];\n }\n\n setAuthKey(authKey, dcId = this._dcId) {\n this._authKeys[dcId] = authKey;\n\n void this._onUpdate();\n }\n\n getSessionData() {\n const sessionData = {\n mainDcId: this._dcId,\n keys: {},\n hashes: {},\n };\n\n Object\n .keys(this._authKeys)\n .forEach((dcId) => {\n const authKey = this._authKeys[dcId];\n if (!authKey || !authKey._key) return;\n\n sessionData.keys[dcId] = authKey._key.toString('hex');\n sessionData.hashes[dcId] = authKey._hash.toString('hex');\n });\n\n return sessionData;\n }\n\n _onUpdate() {\n this._callback(this.getSessionData());\n }\n\n delete() {\n this._callback(undefined);\n }\n}\n\nmodule.exports = CallbackSession;\n","const idb = require('idb-keyval');\nconst StorageSession = require('./StorageSession');\n\nconst CACHE_NAME = 'GramJs';\n\nclass IdbSession extends StorageSession {\n _delete() {\n return idb.del(`${CACHE_NAME}:${this._storageKey}`);\n }\n\n _fetchFromCache() {\n return idb.get(`${CACHE_NAME}:${this._storageKey}`);\n }\n\n _saveToCache(data) {\n return idb.set(`${CACHE_NAME}:${this._storageKey}`, data);\n }\n}\n\nmodule.exports = IdbSession;\n","const StorageSession = require('./StorageSession');\n\nclass LocalStorageSession extends StorageSession {\n _delete() {\n return localStorage.removeItem(this._storageKey);\n }\n\n _fetchFromCache() {\n return localStorage.getItem(this._storageKey);\n }\n\n _saveToCache(data) {\n return localStorage.setItem(this._storageKey, data);\n }\n}\n\nmodule.exports = LocalStorageSession;\n","const Session = require('./Abstract');\n\nclass MemorySession extends Session {\n constructor() {\n super();\n\n this._serverAddress = undefined;\n this._dcId = 0;\n this._port = undefined;\n this._takeoutId = undefined;\n\n this._entities = new Set();\n this._updateStates = {};\n }\n\n get dcId() {\n return this._dcId;\n }\n\n get serverAddress() {\n return this._serverAddress;\n }\n\n get port() {\n return this._port;\n }\n\n get authKey() {\n return this._authKey;\n }\n\n set authKey(value) {\n this._authKey = value;\n }\n\n setDC(dcId, serverAddress, port) {\n this._dcId = dcId | 0;\n this._serverAddress = serverAddress;\n this._port = port;\n }\n\n /* CONTEST\n get takeoutId() {\n return this._takeoutId\n }\n\n set takeoutId(value) {\n this._takeoutId = value\n }\n\n\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 = 139;\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#a8edd0f5 flags:# pinned:flags.2?true unread_mark:flags.3?true peer:Peer top_message:int read_inbox_max_id:int read_outbox_max_id:int unread_count:int unread_mentions_count:int unread_reactions_count:int notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?int = Dialog;\ndialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog;\nphotoEmpty#2331b22d id:long = Photo;\nphoto#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector 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;\ninputReportReasonIllegalDrugs#a8eb2be = ReportReason;\ninputReportReasonPersonalDetails#9ec7863d = 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 videos:flags.6?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 rtmp_stream:flags.12?true listeners_hidden:flags.13?true id:long access_hash:long participants_count:int title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int unmuted_video_count:flags.10?int unmuted_video_limit:int version:int = GroupCall;\ninputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall;\ngroupCallParticipant#eba636fe flags:# muted:flags.0?true left:flags.1?true can_self_unmute:flags.2?true just_joined:flags.4?true versioned:flags.5?true min:flags.8?true muted_by_you:flags.9?true volume_by_admin:flags.10?true self:flags.12?true video_joined:flags.15?true peer:Peer date:int active_date:flags.3?int source:int volume:flags.7?int about:flags.11?string raise_hand_rating:flags.13?long video:flags.6?GroupCallParticipantVideo presentation:flags.14?GroupCallParticipantVideo = GroupCallParticipant;\nphone.groupCall#9e727aad call:GroupCall participants:Vector 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#4f2b9479 flags:# min:flags.0?true can_see_list:flags.2?true results:Vector recent_reactions:flags.1?Vector = MessageReactions;\nmessages.messageReactionsList#31bd492d flags:# count:int reactions:Vector chats:Vector users:Vector next_offset:flags.0?string = messages.MessageReactionsList;\navailableReaction#c077ec01 flags:# inactive:flags.0?true reaction:string title:string static_icon:Document appear_animation:Document select_animation:Document activate_animation:Document effect_animation:Document around_animation:flags.1?Document center_icon:flags.1?Document = AvailableReaction;\nmessages.availableReactionsNotModified#9f071957 = messages.AvailableReactions;\nmessages.availableReactions#768e3aad hash:int reactions:Vector = messages.AvailableReactions;\nmessages.translateNoResult#67ca4737 = messages.TranslatedText;\nmessages.translateResultText#a214f7d0 text:string = messages.TranslatedText;\nmessagePeerReaction#51b67eff flags:# big:flags.0?true unread:flags.1?true peer_id:Peer reaction:string = MessagePeerReaction;\ngroupCallStreamChannel#80eb48af channel:int scale:int last_timestamp_ms:long = GroupCallStreamChannel;\nphone.groupCallStreamChannels#d0e482b2 channels:Vector = phone.GroupCallStreamChannels;\nphone.groupCallStreamRtmpUrl#2dbf3432 url:string key:string = phone.GroupCallStreamRtmpUrl;\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;\ncontacts.resolvePhone#8af94344 phone:string = contacts.ResolvedPeer;\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.reportSpam#cf1592db peer:InputPeer = Bool;\nmessages.getPeerSettings#efd9a6a2 peer:InputPeer = messages.PeerSettings;\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.saveGif#327a30cb id:InputDocument unsave:Bool = Bool;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\nmessages.sendInlineBotResult#7aa11297 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true hide_via:flags.11?true peer:InputPeer reply_to_msg_id:flags.0?int random_id:long query_id:long id:string schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.editMessage#48f71778 flags:# no_webpage:flags.1?true peer:InputPeer id:int message:flags.11?string media:flags.14?InputMedia reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector 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.hidePeerSettingsBar#4facb138 peer:InputPeer = Bool;\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.getExportedChatInvites#a2b5a3f6 flags:# revoked:flags.3?true peer:InputPeer admin_id:InputUser offset_date:flags.2?int offset_link:flags.2?string limit:int = messages.ExportedChatInvites;\nmessages.editExportedChatInvite#bdca2f75 flags:# revoked:flags.2?true peer:InputPeer link:string expire_date:flags.0?int usage_limit:flags.1?int request_needed:flags.3?Bool title:flags.4?string = messages.ExportedChatInvite;\nmessages.deleteRevokedExportedChatInvites#56987bd5 peer:InputPeer admin_id:InputUser = Bool;\nmessages.deleteExportedChatInvite#d464a42b peer:InputPeer link:string = Bool;\nmessages.getChatInviteImporters#df04dd4e flags:# requested:flags.0?true peer:InputPeer link:flags.1?string q:flags.2?string offset_date:int offset_user:InputUser limit:int = messages.ChatInviteImporters;\nmessages.getMessageReadParticipants#2c6f97b7 peer:InputPeer msg_id:int = Vector;\nmessages.hideChatJoinRequest#7fe7e815 flags:# approved:flags.0?true peer:InputPeer user_id:InputUser = Updates;\nmessages.hideAllChatJoinRequests#e085f4ea flags:# approved:flags.0?true peer:InputPeer link:flags.1?string = Updates;\nmessages.toggleNoForwards#b11eafa2 peer:InputPeer enabled:Bool = Updates;\nmessages.saveDefaultSendAs#ccfddf96 peer:InputPeer send_as:InputPeer = Bool;\nmessages.sendReaction#25690ce4 flags:# big:flags.1?true peer:InputPeer msg_id:int reaction:flags.0?string = Updates;\nmessages.getMessagesReactions#8bba90e6 peer:InputPeer id:Vector = Updates;\nmessages.getMessageReactionsList#e0ee6b77 flags:# peer:InputPeer id:int reaction:flags.0?string offset:flags.1?string limit:int = messages.MessageReactionsList;\nmessages.setChatAvailableReactions#14050ea6 peer:InputPeer available_reactions:Vector = Updates;\nmessages.getAvailableReactions#18dea0ac hash:int = messages.AvailableReactions;\nmessages.setDefaultReaction#d960c4d4 reaction:string = 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.getAppConfig#98914110 = JSONValue;\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:# rtmp_stream:flags.2?true peer:InputPeer random_id:int title:flags.0?string schedule_date:flags.1?int = Updates;\nphone.joinGroupCall#b132ff7b flags:# muted:flags.0?true video_stopped:flags.2?true call:InputGroupCall join_as:InputPeer invite_hash:flags.1?string params:DataJSON = Updates;\nphone.leaveGroupCall#500377f9 call:InputGroupCall source:int = Updates;\nphone.discardGroupCall#7a777135 call:InputGroupCall = Updates;\nphone.getGroupCall#41845db call:InputGroupCall limit:int = phone.GroupCall;\nphone.getGroupParticipants#c558d8ab call:InputGroupCall ids:Vector 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;\nstats.getBroadcastStats#ab42441a flags:# dark:flags.0?true channel:InputChannel = stats.BroadcastStats;\nstats.loadAsyncGraph#621d5fa0 flags:# token:string x:flags.0?long = StatsGraph;\nstats.getMegagroupStats#dcdf8607 flags:# dark:flags.0?true channel:InputChannel = stats.MegagroupStats;`;","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 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 const vectorMatch = currentConfig.type.match(/[Vv]ector<([\\w\\d.]+)>/);\n\n if (vectorMatch) {\n currentConfig.isVector = true;\n\n // If the type's first letter is not uppercase, then\n // it is a constructor and we use (read/write) its ID.\n currentConfig.useVectorId = currentConfig.type.charAt(0) === 'V';\n\n // Update the type to match the one inside the vector\n [, currentConfig.type] = vectorMatch;\n }\n\n // See use_vector_id. An example of such case is ipPort in\n // help.configSpecial\n if (/^[a-z]$/.test(currentConfig.type.split('.')\n .pop()\n .charAt(0))\n ) {\n currentConfig.skipConstructorId = true;\n }\n\n // The name may contain \"date\" in it, if this is the case and\n // the type is \"int\", we can safely assume that this should be\n // treated as a \"date\" object. Note that this is not a valid\n // Telegram object, but it's easier to work with\n // if (\n // this.type === 'int' &&\n // (/(\\b|_)([dr]ate|until|since)(\\b|_)/.test(name) ||\n // ['expires', 'expires_at', 'was_online'].includes(name))\n // ) {\n // this.type = 'date';\n // }\n }\n return currentConfig;\n}\n\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, [802,313], () => (__webpack_require__(1742)))\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 + \".\" + {\"313\":\"5cd1718104a79212da23\",\"802\":\"acd83f1b28a8893b9dba\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks and sibling chunks for the entrypoint\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","var scriptUrl;\nif (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + \"\";\nvar document = __webpack_require__.g.document;\nif (!scriptUrl && document) {\n\tif (document.currentScript)\n\t\tscriptUrl = document.currentScript.src\n\tif (!scriptUrl) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tif(scripts.length) scriptUrl = scripts[scripts.length - 1].src\n\t}\n}\n// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration\n// or pass an empty string (\"\") and set the __webpack_public_path__ variable from your code to use your own logic.\nif (!scriptUrl) throw new Error(\"Automatic publicPath is not supported in this browser\");\nscriptUrl = scriptUrl.replace(/#.*$/, \"\").replace(/\\?.*$/, \"\").replace(/\\/[^\\/]+$/, \"/\");\n__webpack_require__.p = scriptUrl;","// no baseURI\n\n// object to store loaded chunks\n// \"1\" means \"already loaded\"\nvar installedChunks = {\n\t742: 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","prefix","btoa","String","fromCharCode","omitVirtualClassFields","instance","flags","CONSTRUCTOR_ID","SUBCLASS_OF_ID","className","classType","getBytes","rest","pathBytesToSvg","width","height","replace","path","len","length","i","num","buildPath","DEFAULT_THUMB_SIZE","w","h","buildApiThumbnailFromStripped","sizes","thumb","find","s","GramJs","realSizes","filter","dataUri","strippedPhotoToJpg","undefined","buildApiPhoto","photo","map","buildApiPhotoSize","id","thumbnail","photoSize","type","localMessages","chats","users","messages","documents","stickerSets","photos","webDocuments","LOTTIE_STICKER_MIME_TYPE","VIDEO_STICKER_MIME_TYPE","buildStickerFromDocument","document","stickerAttribute","attributes","attr","fileAttribute","isLottie","isVideo","imageSizeAttribute","videoSizeAttribute","sizeAttribute","stickerSetInfo","stickerset","emoji","alt","cachedThumb","thumbs","self","isWebmSupported","pathThumb","buildApiThumbnailFromCached","buildApiThumbnailFromPath","stickerSetId","stickerSetAccessHash","accessHash","buildStickerSet","set","archived","animated","installedDate","videos","title","count","shortName","isVideos","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","Spoiler","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","buildMessageContent","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","sticker","shouldHideKeyboardButtons","views","isFromScheduled","fromScheduled","reactions","buildMessageReactions","replyToMessageId","replyToChatId","replyToTopMessageId","mentioned","hasUnreadMention","isMentioned","viaBotId","comments","threadInfo","buildThreadInfo","noforwards","isProtected","recentReactions","results","canSeeList","buildReactionCount","buildMessagePeerReaction","reactionCount","chosen","reaction","isChosen","userReaction","buildApiAvailableReaction","availableReaction","selectAnimation","staticIcon","inactive","aroundAnimation","centerIcon","buildApiDocument","isInactive","buildMessageMediaContent","poll","contact","isRound","buildApiMessageEntity","buildMessageDraft","draft","formattedText","replyingToId","ttlSeconds","buildSticker","buildPhoto","buildVideoFromDocument","buildVideo","audioAttribute","voice","thumbnailSizes","fileName","getFilenameFromDocument","buildAudio","waveform","buildVoice","buildDocumentFromMedia","phoneNumber","buildContact","buildPoll","buildPollFromMedia","webPage","buildWebPage","invoice","description","test","photoUrl","isTest","buildInvoice","buildInvoiceFromMedia","location","point","buildGeoPoint","geo","buildGeo","provider","address","venueId","venueType","buildVenue","period","heading","buildGeoLive","buildLocationFromMedia","size","isMovSupported","videoAttr","a","gifAttr","supportsStreaming","roundMessage","isGif","mediaType","mediaSize","has","imageAttribute","timestamp","long","lat","accuracyRadius","pollResults","answers","rawAnswers","answer","option","summary","isPublic","publicVoters","buildPollResults","rawResults","totalVoters","recentVoters","solution","solutionEntities","correct","voters","isCorrect","votersCount","recentVoterIds","defaultBase","filenameAttribute","extension","split","buildUploadingMedia","attachment","filename","blobUrl","previewBlobUrl","quick","inputWaveform","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","emoticon","buildApiChatFolder","channels","broadcasts","pinnedChatIds","pinnedPeers","includedChatIds","includePeers","excludedChatIds","excludePeers","buildApiChatFolderFromSuggested","buildApiChatBotCommands","botInfos","botCommands","botInfo","botId","concat","commands","mtpCommand","buildApiExportedInvite","invite","revoked","expireDate","link","permanent","startDate","usage","usageLimit","requested","requestNeeded","adminId","isRevoked","isPermanent","isRequestNeeded","buildApiChatSettings","autoarchived","reportSpam","addContact","blockContact","isAutoArchived","canReportSpam","canAddContact","canBlockContact","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","buildJson","json","acc","el","buildApiGroupCallParticipant","participant","versioned","canSelfUnmute","justJoined","muted","mutedByYou","source","volume","volumeByAdmin","videoJoined","presentation","raiseHandRating","isLeft","isMutedByMe","hasJustJoined","isVolumeByAdmin","isVersioned","isVideoJoined","isUser","buildApiGroupCallParticipantVideo","participantVideo","audioSource","endpoint","paused","sourceGroups","isPaused","buildApiGroupCallParticipantVideoSourceGroup","participantVideoSourceGroup","semantics","sources","buildApiGroupCall","connectionState","version","streamDcId","scheduleDate","canChangeJoinMuted","joinMuted","canStartVideo","scheduleStartSubscribed","isLoaded","onUpdate","sentMessageIds","shouldIgnoreNextChannelUpdate","dispatchUserAndChatUpdates","e","updater","originRequest","connection","timeOffset","state","shouldForceReply","buildApiMessageFromShort","selective","_entities","dcId","buildChatPhotoForLocalDb","localDbChatId","newProfilePhoto","some","msgId","ids","existingIds","missingIds","profilePhotoIds","setTimeout","popup","error","notification","currentDate","inboxDate","buildApiMessageFromNotification","localMessage","Error","newContent","add","isAlreadySent","isScheduled","sendingState","messageUpdate","pollId","apiPoll","pollUpdate","options","stillUnreadCount","isPinned","pinned","order","dp","folderPeers","folderPeer","folder","orderedIds","replacedMembers","addedMember","deletedMemberId","messageIds","interaction","JSON","parse","timestamps","l","t","typingStatus","channel","unread","apiUserId","updatedUser","settings","peerType","buildPrivacyKey","params","groupCallId","recentRequesterIds","recentRequesters","requestsPending","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","console","warn","save","cacheData","stringify","Response","put","clear","delete","MEDIA_ENTITY_TYPES","getMimeType","fallbackMimeType","signature","subarray","byte","GramJsLogger","gramJsUpdateEventBuilder","build","client","isConnected","destroy","invokeRequest","disconnect","onSessionUpdate","sessionData","handleGramJsUpdate","handleTerminatedSession","shouldReturnTrue","shouldThrow","shouldIgnoreUpdates","invoke","handleUpdatesFromRequest","dispatchErrorUpdate","manyUpdates","singleUpdate","updates","injectUpdateEntities","downloadMedia","args","onProgress","mediaFormat","start","end","fullSize","mediaMatch","arrayBuffer","entityType","entityId","sizeType","parsedParams","URLSearchParams","zoom","scale","downloadStaticMap","Stream","acceptsBuffer","progressCallback","workers","getMessageMediaMimeType","downloadStickerSetThumb","Lottie","downloadProfilePhoto","download","parsed","BlobUrl","Progressive","buffer","parseMedia","canCache","prepared","mediaData","URL","createObjectURL","downloadMediaWithClient","uploadFile","file","updateTwoFaSettings","fetchCurrentUser","userFull","currentUser","_currentUserId","onCurrentUserUpdate","isSlowMode","hasErrorKey","MAX_INT_32","fetchChats","limit","offsetDate","withPinned","lastLocalServiceMessage","offsetPeer","excludePinned","resultPinned","updateLocalDb","lastMessagesByChatId","peersByKey","preparePeers","draftsById","replyingToById","dialogs","orderedPinnedIds","lastMessage","isListed","chatIds","totalChatCount","fetchFullChat","fullChat","onlineCount","exportedInvite","slowmodeSeconds","slowmodeNextSendDate","migratedFromChatId","migratedFromMaxId","canViewParticipants","canViewStats","linkedChatId","hiddenPrehistory","availableReactions","defaultSendAs","statsDc","inviteLink","members","fetchMembers","kickedMembers","bannedUsers","adminMembers","adminUsers","mtpLinkedChat","slowMode","nextSendDate","migratedFrom","maxMessageId","canViewMembers","canViewStatistics","isPreHistoryHidden","enabledReactions","sendAsId","statisticsDcId","getFullChannelInfo","getFullChatInfo","fetchChatSettings","searchChats","query","q","localPeerIds","myResults","allChats","allUsers","localChats","r","localUsers","u","globalChats","globalUsers","fetchChat","requestChatUpdate","lastLocalMessage","noLastMessage","peers","lastRemoteMessage","saveDraft","clearDraft","updateChatMutedState","createChannel","noErrorUpdate","broadcast","newChannel","joinChannel","deleteChatUser","deleteChat","leaveChannel","deleteChannel","createGroupChat","newChat","editChatPhoto","uploadedPhoto","inputEntity","toggleChatPinned","shouldBePinned","toggleChatArchived","fetchChatFolders","byId","fetchRecommendedChatFolders","editChatFolder","folderUpdate","contacts","nonContacts","groups","bots","excludeArchived","excludeMuted","excludeRead","buildFilterFromApiFolder","deleteChatFolder","isActionSuccessful","recommendedChatFolders","folders","toggleDialogUnread","getChatByPhoneNumber","processResolvedPeer","getChatByUsername","togglePreHistoryHidden","isEnabled","enabled","updateChatDefaultBannedRights","updateChatMemberBannedRights","updateChatAdmin","updateChatTitle","updateChatAbout","toggleSignatures","memberFilter","fetchGroupsForDiscussion","setDiscussionGroup","group","migrateChat","openChatByInvite","isChannel","addChatMembers","all","deleteChatMember","viewMessages","sendMessages","sendMedia","sendStickers","sendGifs","sendGames","sendInline","embedLinks","sendPolls","changeInfo","inviteUsers","pinMessages","store","importChatInvite","setChatEnabledReactions","toggleIsProtected","File","constructor","fileBits","super","this","fetchMessages","pagination","RequestClass","c","threadInfos","fetchMessage","queue","sendMessage","replyingTo","gif","scheduledAt","noWebPage","sendAs","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","fetchBlob","lastModified","blobToFile","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","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","importContact","imported","updateContact","shouldSharePhoneNumber","addPhonePrivacyException","deleteContact","fetchProfilePhotos","userOrChat","fetchStickerSets","allStickers","sets","fetchRecentStickers","stickers","processStickerResult","fetchFavoriteStickers","fetchFeaturedStickers","faveSticker","unfave","fetchStickers","stickerSetShortName","packs","documentId","fetchAnimatedEmojis","fetchAnimatedEmojiEffects","searchStickers","fetchSavedGifs","gifs","processGifResult","saveGif","shouldUnsave","unsave","installStickerSet","uninstallStickerSet","searchGifs","config","resolvedPeer","gifSearchUsername","foundGif","fetchStickersForEmoji","fetchEmojiKeywords","fromVersion","langCode","keywords","emojiKeyword","keyword","emoticons","checkChatUsername","setChatUsername","updatePrivateLink","fetchExportedChatInvites","admin","exportedInvites","invites","editExportedChatInvite","replaceInvite","oldInvite","newInvite","exportChatInvite","deleteExportedChatInvite","deleteRevokedExportedChatInvites","fetchChatInviteImporters","offsetUser","isRequested","importers","importer","buildChatInviteImporter","hideChatJoinRequest","isApproved","approved","hideAllChatJoinRequests","hideChatReportPanel","EMAIL_UNCONFIRMED","EMAIL_HASH_EXPIRED","NEW_SALT_INVALID","NEW_SETTINGS_INVALID","CODE_INVALID","emailCodeController","getPasswordInfo","hasPassword","onRequestEmailCode","checkPassword","currentPassword","isCheckPassword","onError","clearPassword","updatePassword","email","newPassword","emailCodeCallback","onEmailCodeError","updateRecoveryEmail","provideRecoveryEmailCode","getGroupCall","discardGroupCall","editGroupCallParticipant","presentationPaused","videoStopped","videoPaused","raiseHand","editGroupCallTitle","exportGroupCallInvite","fetchGroupCallParticipants","leaveGroupCall","joinGroupCall","inviteHash","joinAs","createGroupCall","toJSNumber","joinGroupCallPresentation","toggleGroupCallStartSubscription","subscribed","leaveGroupCallPresentation","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","publicToken","public_token","buildPaymentForm","getReceipt","receipt","shipping","credentialsTitle","shippingPrices","shippingMethod","buildReceipt","buildEmojiSounds","appConfig","emojies_sounds","access_hash","atob","file_reference_base64","BETA_LANG_CODES","updateProfile","checkUsername","updateUsername","updateProfilePhoto","uploadProfilePhoto","fetchWallpapers","filteredWallpapers","wallpapers","pattern","uploadWallpaper","fetchBlockedContacts","blockedIds","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","fetchAppConfig","emojiSounds","defaultReaction","reactions_default","seenByMaxChatMembers","chat_read_mark_size_threshold","seenByExpiresAt","chat_read_mark_expire_period","buildApiConfig","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","sendWatchingEmojiInteraction","sendEmojiInteraction","v","getAvailableReactions","sendReaction","fetchMessageReactions","fetchMessageReactionsList","setDefaultReaction","buildGraph","isPercentage","x","y","columns","hasSecondYAxis","y_scaled","types","y0","zoomToken","labelFormatter","xTickFormatter","tooltipFormatter","xTooltipFormatter","labels","hideCaption","subchart","show","isStacked","stacked","datasets","item","names","color","colors","substring","indexOf","calculateMinimapRange","defaultZoom","range","minIndex","maxIndex","minimapRange","begin","labelFromIndex","labelToIndex","buildStatisticsOverview","previous","change","percentage","toFixed","fetchChannelStatistics","stats","growthGraph","followersGraph","muteGraph","topHoursGraph","languagesGraph","viewsBySourceGraph","newFollowersBySourceGraph","interactionsGraph","followers","viewsPerPost","sharesPerPost","enabledNotifications","part","total","recentTopMessages","recentMessageInteractions","fetchGroupStatistics","membersGraph","messagesGraph","actionsGraph","viewers","posters","fetchStatisticsAsyncGraph","initApi","_onUpdate","initialArgs","initUpdater","handleUpdate","initAuth","initChats","initMessages","initUsers","initStickers","initManagement","initTwoFaSettings","initCalls","initPayments","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","interval","isPending","shouldRunFirst","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","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","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","ConnectionTCPObfuscated","MTProtoSender","UpdateConnectionState","authFlow","checkAuthorization","downloadFile","WEBDOCUMENT_REQUEST_PART_SIZE","sizeTypes","apiId","apiHash","opts","DEFAULT_OPTIONS","_useIPV6","useIPV6","baseLogger","_log","floodSleepLimit","_eventBuilders","_phoneCodeHash","parseInt","_requestRetries","requestRetries","_connectionRetries","connectionRetries","_retryDelay","retryDelay","proxy","_proxy","_timeout","timeout","_autoReconnect","autoReconnect","_connection","_floodWaitedRequests","_initWith","InvokeWithLayer","layer","InitConnection","release","systemLangCode","_config","phoneCodeHashes","_exportedSenderPromises","_exportedSenderReleaseTimeouts","_additionalDcsDisabled","_loopStarted","_isSwitchingDc","_destroyed","_initSession","_sender","logger","retries","delay","connectTimeout","authKeyCallback","_authKeyCallback","bind","updateCallback","_handleUpdate","isMainSender","userDisconnected","_user_connected","isReconnecting","_disconnected","serverAddress","connect","setAuthKey","authKey","send","GetConfig","_updateLoop","load","setDC","lastPongAt","ping","PingDelayDisconnect","pingId","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","disconnectDelay","pingAt","lastInterval","attempts","wakeUpWarningTimeout","disconnected","clearTimeout","connected","getTime","_lastRequest","GetState","sender","newDc","DC","setKey","dc","_authenticated","auth","ExportAuthorization","req","ImportAuthorization","shouldReconnect","existingSender","_connectSender","_createExportedSender","isConnecting","_borrowExportedSender","onConnectionBreak","_cleanupExportedSender","getSender","inputLocation","messageOrMedia","Message","MessageMediaWebPage","WebPage","MessageMediaPhoto","Photo","_downloadPhoto","MessageMediaDocument","Document","_downloadDocument","MessageMediaContact","_downloadContact","WebDocument","WebDocumentNoProxy","_downloadWebDocument","isBig","loc","chatPhoto","UserProfilePhoto","ChatPhoto","InputPeerPhotoFileLocation","thumbVersion","InputStickerSetThumb","InputStickerSetID","thumbDcId","_pickFileSize","_downloadCachedPhotoSize","PhotoStrippedSize","PhotoSizeEmpty","PhotoCachedSize","InputPhotoFileLocation","thumbSize","doc","InputDocumentFileLocation","buff","downloaded","upload","GetWebFile","InputWebFileLocation","InputWebFileGeoPointLocation","geoPoint","InputGeoPoint","FloodWaitError","attempt","sendWithInvokeSupport","ServerError","FloodTestPhoneWaitError","PhoneMigrateError","NetworkMigrateError","UserMigrateError","_switchDC","MsgWaitError","isReady","GetUsers","InputUserSelf","authParams","apiCredentials","fileParams","event","Updates","UpdatesCombined","_processUpdate","UpdateShort","others","_dispatchUpdate","ptsDate","builder","race","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","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","to","ReadCancelledError","TypeNotFoundError","invalidConstructorId","remaining","alert","InvalidChecksumError","checksum","validChecksum","InvalidBufferError","payload","readInt32LE","SecurityError","BadMessageError","errorMessage","ErrorMessages","CdnFileTamperedError","RPCError","_fmtRequest","InvalidDCError","BadRequestError","UnauthorizedError","ForbiddenError","NotFoundError","AuthKeyError","FloodError","TimedOutError","capture","SlowModeWaitError","FileMigrateError","EmailUnconfirmedError","rpcErrorRe","Common","RPCBaseErrors","RPCErrorList","RPCMessageToError","rpcError","msgRegex","Cls","EventBuilder","func","blacklistChats","resolved","NewMessage","Raw","StopPropagation","_queue","canGet","resolveGet","canPush","resolvePush","returned","pop","coreObjects","tlobjects","stream","_last","readByte","readInt","readUInt32LE","readLargeInt","readFloat","readFloatLE","readDouble","readDoubleLE","getBuffer","tgReadBytes","firstByte","tgReadString","tgReadBool","tgReadDate","tgReadObject","constructorId","clazz","seek","tellPosition","setPosition","fromReader","tgReadVector","close","position","_stream","write","getValue","_level","level","isBrowser","browser","__nwjs","debug","messageFormat","canSend","levels","stack","format","toISOString","toUpperCase","log","MessageContainer","TLMessage","BinaryWriter","USE_INVOKE_AFTER_WITH","_state","_pendingStates","_ready","setReady","append","after","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","UpdateServerTimeOffset","BadServerSalt","BadMsgNotification","MsgDetailedInfo","MsgNewDetailedInfo","NewSessionCreated","FutureSalts","MsgsStateReq","MsgResendReq","MsgsAllInfo","LogOut","_dcId","_retries","_delay","_connectTimeout","_updateCallback","_autoReconnectCallback","autoReconnectCallback","_isMainSender","_onConnectionBreak","_send_loop_handle","_recv_loop_handle","_send_queue","_pending_state","_pending_ack","_last_acks","_handlers","_handleRPCResult","_handleContainer","_handleGzipPacked","_handlePong","_handleBadServerSalt","_handleBadNotification","_handleDetailedInfo","_handleNewDetailedInfo","_handleNewSessionCreated","_handleAck","_handleFutureSalts","_handleStateForgotten","_handleMsgAll","force","_connect","_disconnect","plain","_sendLoop","_recvLoop","ack","msgIds","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","origin","StorageSession","CACHE_NAME","_storageKey","cached","_sessionData","_callback","_authKeys","mainDcId","hashes","skipOnUpdate","_serverAddress","idb","_delete","del","_fetchFromCache","_saveToCache","localStorage","removeItem","getItem","setItem","_takeoutId","_updateStates","_authKey","sessionInfo","_sessionString","_loadFromSessionString","skipUpdateStorage","_updateStorage","asHex","mainDcIdStr","mainDcKey","StringSession","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","inflate","gzipped","toBytes","gzip","ungzip","containerLength","before","tlMessage","RpcError","innerCode","snakeToCamelCase","_","variableSnakeToCamelCase","CORE_TYPES","AUTH_KEY_TYPES","findAll","regex","matches","RegExp","exec","fromLine","line","argsMatch","currentConfig","hexId","representation","brace","argType","buildArgConfig","flagMatch","vectorMatch","ignoreIds","o","objAll","objByName","objByType","commentIndex","trim","followingTypes","dt","fill","__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":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B,wBAAK,GACxFm/E,EAA6BD,EAAmBt9E,KAAKqsD,KAAKixB,GAC9DA,EAAmBt9E,KAvBCG,IACnB,IAAKs7E,EAAU+B,EAAaC,GAAWt9E,EACvC,IAAI,IAAIg7E,KAAYqC,EAChBtC,EAAoBV,EAAEgD,EAAarC,KACrCD,EAAoB/6B,EAAEg7B,GAAYqC,EAAYrC,IAIhD,IADGsC,GAASA,EAAQvC,GACdO,EAAS1gF,QACdsiF,EAAgB5B,EAAStc,OAAS,EACnCoe,EAA2Bp9E,K,GvHnBxBlI,EAAOijF,EAAoBrlC,EAC/BqlC,EAAoBrlC,EAAI,IAChBlsB,QAAQ0Q,IAAI,CAClB6gD,EAAoBv2D,EAAE,KACtBu2D,EAAoBv2D,EAAE,OACpBy3B,KAAKnkD,GwHJiBijF,EAAoBrlC,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/payments.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/payments.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/appConfig.ts","webpack://telegram-t/./src/api/gramjs/methods/settings.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/bots.ts","webpack://telegram-t/./src/api/gramjs/methods/bots.ts","webpack://telegram-t/./src/api/gramjs/methods/reactions.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/statistics.ts","webpack://telegram-t/./src/api/gramjs/methods/statistics.ts","webpack://telegram-t/./src/api/gramjs/provider.ts","webpack://telegram-t/./src/api/gramjs/worker/worker.ts","webpack://telegram-t/./src/lib/gramjs/Helpers.js","webpack://telegram-t/./src/lib/gramjs/Password.js","webpack://telegram-t/./src/lib/gramjs/Utils.js","webpack://telegram-t/./src/lib/gramjs/Version.js","webpack://telegram-t/./src/lib/gramjs/client/2fa.ts","webpack://telegram-t/./src/lib/gramjs/client/TelegramClient.js","webpack://telegram-t/./src/lib/gramjs/client/auth.ts","webpack://telegram-t/./src/lib/gramjs/client/downloadFile.ts","webpack://telegram-t/./src/lib/gramjs/client/uploadFile.ts","webpack://telegram-t/./src/lib/gramjs/crypto/AuthKey.js","webpack://telegram-t/./src/lib/gramjs/crypto/CTR.js","webpack://telegram-t/./src/lib/gramjs/crypto/Factorizator.js","webpack://telegram-t/./src/lib/gramjs/crypto/IGE.js","webpack://telegram-t/./src/lib/gramjs/crypto/converters.ts","webpack://telegram-t/./src/lib/gramjs/crypto/crypto.js","webpack://telegram-t/./src/lib/gramjs/crypto/words.ts","webpack://telegram-t/./src/lib/gramjs/errors/Common.js","webpack://telegram-t/./src/lib/gramjs/errors/RPCBaseErrors.js","webpack://telegram-t/./src/lib/gramjs/errors/RPCErrorList.js","webpack://telegram-t/./src/lib/gramjs/errors/index.js","webpack://telegram-t/./src/lib/gramjs/events/Raw.js","webpack://telegram-t/./src/lib/gramjs/events/common.js","webpack://telegram-t/./src/lib/gramjs/events/index.js","webpack://telegram-t/./src/lib/gramjs/extensions/AsyncQueue.js","webpack://telegram-t/./src/lib/gramjs/extensions/BinaryReader.js","webpack://telegram-t/./src/lib/gramjs/extensions/BinaryWriter.js","webpack://telegram-t/./src/lib/gramjs/extensions/Logger.js","webpack://telegram-t/./src/lib/gramjs/extensions/MessagePacker.js","webpack://telegram-t/./src/lib/gramjs/extensions/PromisedWebSockets.js","webpack://telegram-t/./src/lib/gramjs/extensions/index.js","webpack://telegram-t/./src/lib/gramjs/index.js","webpack://telegram-t/./src/lib/gramjs/crypto/RSA.ts","webpack://telegram-t/./src/lib/gramjs/network/Authenticator.ts","webpack://telegram-t/./src/lib/gramjs/network/MTProtoPlainSender.js","webpack://telegram-t/./src/lib/gramjs/network/MTProtoSender.js","webpack://telegram-t/./src/lib/gramjs/network/MTProtoState.js","webpack://telegram-t/./src/lib/gramjs/network/RequestState.js","webpack://telegram-t/./src/lib/gramjs/network/connection/Connection.js","webpack://telegram-t/./src/lib/gramjs/network/connection/TCPAbridged.js","webpack://telegram-t/./src/lib/gramjs/network/connection/TCPObfuscated.js","webpack://telegram-t/./src/lib/gramjs/network/connection/index.js","webpack://telegram-t/./src/lib/gramjs/network/index.js","webpack://telegram-t/./src/lib/gramjs/network/updates.js","webpack://telegram-t/./src/lib/gramjs/sessions/Abstract.js","webpack://telegram-t/./src/lib/gramjs/sessions/CacheApiSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/CallbackSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/IdbSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/LocalStorageSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/Memory.js","webpack://telegram-t/./src/lib/gramjs/sessions/StorageSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/StringSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/index.js","webpack://telegram-t/./src/lib/gramjs/tl/AllTLObjects.js","webpack://telegram-t/./src/lib/gramjs/tl/api.js","webpack://telegram-t/./src/lib/gramjs/tl/apiTl.js","webpack://telegram-t/./src/lib/gramjs/tl/core/GZIPPacked.js","webpack://telegram-t/./src/lib/gramjs/tl/core/MessageContainer.js","webpack://telegram-t/./src/lib/gramjs/tl/core/RPCResult.js","webpack://telegram-t/./src/lib/gramjs/tl/core/TLMessage.js","webpack://telegram-t/./src/lib/gramjs/tl/core/index.js","webpack://telegram-t/./src/lib/gramjs/tl/generationHelpers.js","webpack://telegram-t/./src/lib/gramjs/tl/index.js","webpack://telegram-t/./src/lib/gramjs/tl/schemaTl.js","webpack://telegram-t/webpack/bootstrap","webpack://telegram-t/webpack/runtime/compat get default export","webpack://telegram-t/webpack/runtime/define property getters","webpack://telegram-t/webpack/runtime/ensure chunk","webpack://telegram-t/webpack/runtime/get javascript chunk filename","webpack://telegram-t/webpack/runtime/get mini-css chunk filename","webpack://telegram-t/webpack/runtime/global","webpack://telegram-t/webpack/runtime/hasOwnProperty shorthand","webpack://telegram-t/webpack/runtime/make namespace object","webpack://telegram-t/webpack/runtime/node module decorator","webpack://telegram-t/webpack/runtime/publicPath","webpack://telegram-t/webpack/runtime/importScripts chunk loading","webpack://telegram-t/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var next = __webpack_require__.x;\n__webpack_require__.x = () => {\n\treturn Promise.all([\n\t\t__webpack_require__.e(802),\n\t\t__webpack_require__.e(313)\n\t]).then(next);\n};","export const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION!;\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 PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const DEBUG_PAYMENT_SMART_GLOCAL = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 500;\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 200;\nexport const GLOBAL_STATE_CACHE_CHATS_WITH_MESSAGES_LIMIT = 30;\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-v8';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const AUTODOWNLOAD_FILESIZE_MB_LIMITS = [1, 5, 10, 50, 100, 500];\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\nexport const GROUP_CALL_PARTICIPANTS_LIMIT = 100;\nexport const REACTION_LIST_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\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\nexport const CUSTOM_APPENDIX_ATTRIBUTE = 'data-has-custom-appendix';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const 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 = 100;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const STICKER_SIZE_JOIN_REQUESTS = 140;\nexport const STICKER_SIZE_INVITES = 140;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const NO_STICKER_SET_ID = 'NO_STICKER_SET';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\nexport const VIDEO_WEBM_TYPE = 'video/webm';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const 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\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: T[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(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 | GramJs.DocumentAttributeVideo,\n): ApiThumbnail | undefined {\n const { w, h } = sizeAttribute;\n const dataUri = `data:image/svg+xml;utf8,${pathBytesToSvg(photoSize.bytes, w, h)}`;\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiPhoto(photo: GramJs.Photo): ApiPhoto {\n const sizes = photo.sizes\n .filter((s: any): s is GramJs.PhotoSize => {\n return s instanceof GramJs.PhotoSize || s instanceof GramJs.PhotoSizeProgressive;\n })\n .map(buildApiPhotoSize);\n\n return {\n id: String(photo.id),\n thumbnail: buildApiThumbnailFromStripped(photo.sizes),\n sizes,\n };\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 {\n ApiEmojiInteraction, ApiSticker, ApiStickerSet, GramJsEmojiInteraction,\n} from '../../types';\nimport { NO_STICKER_SET_ID } from '../../../config';\n\nimport { buildApiThumbnailFromCached, buildApiThumbnailFromPath } from './common';\nimport localDb from '../localDb';\n\nconst LOTTIE_STICKER_MIME_TYPE = 'application/x-tgsticker';\nconst VIDEO_STICKER_MIME_TYPE = 'video/webm';\n\nexport function buildStickerFromDocument(document: GramJs.TypeDocument): ApiSticker | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const { mimeType } = document;\n const stickerAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeSticker => (\n attr instanceof GramJs.DocumentAttributeSticker\n ));\n\n const fileAttribute = (mimeType === LOTTIE_STICKER_MIME_TYPE || mimeType === VIDEO_STICKER_MIME_TYPE)\n && document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeFilename => (\n attr instanceof GramJs.DocumentAttributeFilename\n ));\n\n if (!stickerAttribute && !fileAttribute) {\n return undefined;\n }\n\n const isLottie = mimeType === LOTTIE_STICKER_MIME_TYPE;\n const isVideo = mimeType === VIDEO_STICKER_MIME_TYPE;\n\n const imageSizeAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeImageSize => (\n attr instanceof GramJs.DocumentAttributeImageSize\n ));\n\n const videoSizeAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeVideo => (\n attr instanceof GramJs.DocumentAttributeVideo\n ));\n\n const sizeAttribute = imageSizeAttribute || videoSizeAttribute;\n\n const stickerSetInfo = stickerAttribute && stickerAttribute.stickerset instanceof GramJs.InputStickerSetID\n ? stickerAttribute.stickerset\n : undefined;\n const emoji = stickerAttribute?.alt;\n\n const cachedThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoCachedSize => s instanceof GramJs.PhotoCachedSize,\n );\n\n // eslint-disable-next-line no-restricted-globals\n if (mimeType === VIDEO_STICKER_MIME_TYPE && !(self as any).isWebmSupported && !cachedThumb) {\n const staticThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize,\n );\n\n if (!staticThumb) {\n return undefined;\n }\n }\n\n const pathThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoPathSize => s instanceof GramJs.PhotoPathSize,\n );\n\n const thumbnail = cachedThumb ? (\n buildApiThumbnailFromCached(cachedThumb)\n ) : pathThumb && sizeAttribute ? (\n buildApiThumbnailFromPath(pathThumb, sizeAttribute)\n ) : undefined;\n\n const { w: width, h: height } = cachedThumb as GramJs.PhotoCachedSize || sizeAttribute || {};\n\n return {\n id: String(document.id),\n stickerSetId: stickerSetInfo ? String(stickerSetInfo.id) : NO_STICKER_SET_ID,\n stickerSetAccessHash: stickerSetInfo && String(stickerSetInfo.accessHash),\n emoji,\n isLottie,\n isVideo,\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 videos,\n id,\n accessHash,\n title,\n thumbs,\n count,\n shortName,\n } = set;\n\n return {\n archived,\n isLottie: animated,\n isVideos: videos,\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\nexport function buildApiEmojiInteraction(json: GramJsEmojiInteraction): ApiEmojiInteraction {\n return {\n timestamps: json.a.map((l) => l.t),\n };\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 isLottie: boolean;\n isVideo: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isLottie?: true;\n isVideos?: 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\ninterface ApiGeoPoint {\n long: number;\n lat: number;\n accessHash: string;\n accuracyRadius?: number;\n}\n\ninterface ApiGeo {\n type: 'geo';\n geo: ApiGeoPoint;\n}\n\ninterface ApiVenue {\n type: 'venue';\n geo: ApiGeoPoint;\n title: string;\n address: string;\n provider: string;\n venueId: string;\n venueType: string;\n}\n\ninterface ApiGeoLive {\n type: 'geoLive';\n geo: ApiGeoPoint;\n heading?: number;\n period: number;\n}\n\nexport type ApiLocation = ApiGeo | ApiVenue | ApiGeoLive;\n\nexport type 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 Spoiler = 'MessageEntitySpoiler',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: string;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n location?: ApiLocation;\n };\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 reactors?: {\n nextOffset?: string;\n count: number;\n reactions: ApiUserReaction[];\n };\n reactions?: ApiReactions;\n}\n\nexport interface ApiReactions {\n canSeeList?: boolean;\n results: ApiReactionCount[];\n recentReactions?: ApiUserReaction[];\n}\n\nexport interface ApiUserReaction {\n userId: string;\n reaction: string;\n}\n\nexport interface ApiReactionCount {\n isChosen?: boolean;\n count: number;\n reaction: string;\n}\n\nexport interface ApiAvailableReaction {\n selectAnimation?: ApiDocument;\n staticIcon?: ApiDocument;\n centerIcon?: ApiDocument;\n aroundAnimation?: ApiDocument;\n reaction: string;\n title: string;\n isInactive?: 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' | 'illegalDrugs' | 'personalDetails' | '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 | ArrayBuffer;\nexport type ApiPreparedMedia = 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 case ApiMessageEntityTypes.Spoiler:\n return new GramJs.MessageEntitySpoiler({ offset, length });\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 'illegalDrugs':\n return new GramJs.InputReportReasonIllegalDrugs();\n case 'personalDetails':\n return new GramJs.InputReportReasonPersonalDetails();\n case 'other':\n return new GramJs.InputReportReasonOther();\n }\n\n return undefined;\n}\n\nexport function buildSendMessageAction(action: ApiSendMessageAction) {\n switch (action.type) {\n case 'cancel':\n return new GramJs.SendMessageCancelAction();\n case 'typing':\n return new GramJs.SendMessageTypingAction();\n case 'recordAudio':\n return new GramJs.SendMessageRecordAudioAction();\n case 'chooseSticker':\n return new GramJs.SendMessageChooseStickerAction();\n }\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 ApiReactions,\n ApiReactionCount,\n ApiUserReaction,\n ApiAvailableReaction,\n ApiSponsoredMessage,\n ApiUser,\n ApiLocation,\n} from '../../types';\n\nimport {\n DELETED_COMMENTS_CHANNEL_ID,\n LOCAL_MESSAGE_ID_BASE,\n SERVICE_NOTIFICATIONS_USER_ID,\n SPONSORED_MESSAGE_CACHE_MS,\n SUPPORTED_IMAGE_CONTENT_TYPES,\n SUPPORTED_VIDEO_CONTENT_TYPES,\n VIDEO_MOV_TYPE,\n VIDEO_WEBM_TYPE,\n} from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { buildStickerFromDocument } from './symbols';\nimport { buildApiPhoto, buildApiPhotoSize, buildApiThumbnailFromStripped } from './common';\nimport { interpolateArray } from '../../../util/waveform';\nimport { buildPeer } from '../gramjsBuilders';\nimport { addPhotoToLocalDb, resolveMessageApiChatId, serializeBytes } from '../helpers';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer, isPeerUser } from './peers';\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 const content = buildMessageContent(notification);\n\n return {\n id: localId,\n chatId: SERVICE_NOTIFICATIONS_USER_ID,\n date: notification.inboxDate || currentDate,\n content,\n isOutgoing: false,\n };\n}\n\ntype UniversalMessage = (\n Pick\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' | 'reactions'\n )>\n);\n\nexport function buildApiMessageWithChatId(chatId: string, mtpMessage: UniversalMessage): ApiMessage {\n const fromId = mtpMessage.fromId ? getApiChatIdFromMtpPeer(mtpMessage.fromId) : undefined;\n const peerId = mtpMessage.peerId ? getApiChatIdFromMtpPeer(mtpMessage.peerId) : undefined;\n const isChatWithSelf = !fromId && chatId === currentUserId;\n const isOutgoing = (mtpMessage.out && !mtpMessage.post) || (isChatWithSelf && !mtpMessage.fwdFrom);\n const content = buildMessageContent(mtpMessage);\n const action = mtpMessage.action\n && buildAction(mtpMessage.action, fromId, peerId, Boolean(mtpMessage.post), isOutgoing);\n if (action) {\n content.action = action;\n }\n\n const { replyToMsgId, replyToTopId, replyToPeerId } = mtpMessage.replyTo || {};\n const isEdited = mtpMessage.editDate && !mtpMessage.editHide;\n const {\n inlineButtons, keyboardButtons, keyboardPlaceholder, isKeyboardSingleUse,\n } = buildReplyButtons(mtpMessage) || {};\n const forwardInfo = mtpMessage.fwdFrom && buildApiMessageForwardInfo(mtpMessage.fwdFrom, isChatWithSelf);\n const { replies, mediaUnread: isMediaUnread, postAuthor } = mtpMessage;\n const groupedId = mtpMessage.groupedId && String(mtpMessage.groupedId);\n const isInAlbum = Boolean(groupedId) && !(content.document || content.audio || content.sticker);\n const shouldHideKeyboardButtons = mtpMessage.replyMarkup instanceof GramJs.ReplyKeyboardHide;\n\n return {\n id: mtpMessage.id,\n chatId,\n isOutgoing,\n content,\n date: mtpMessage.date,\n senderId: fromId || (mtpMessage.out && mtpMessage.post && currentUserId) || chatId,\n views: mtpMessage.views,\n isFromScheduled: mtpMessage.fromScheduled,\n reactions: mtpMessage.reactions && buildMessageReactions(mtpMessage.reactions),\n ...(replyToMsgId && { replyToMessageId: replyToMsgId }),\n ...(replyToPeerId && { replyToChatId: getApiChatIdFromMtpPeer(replyToPeerId) }),\n ...(replyToTopId && { replyToTopMessageId: replyToTopId }),\n ...(forwardInfo && { forwardInfo }),\n ...(isEdited && { isEdited }),\n ...(mtpMessage.editDate && { editDate: mtpMessage.editDate }),\n ...(isMediaUnread && { isMediaUnread }),\n ...(mtpMessage.mentioned && isMediaUnread && { hasUnreadMention: true }),\n ...(mtpMessage.mentioned && { isMentioned: true }),\n ...(groupedId && {\n groupedId,\n isInAlbum,\n }),\n inlineButtons,\n ...(keyboardButtons && { keyboardButtons, keyboardPlaceholder, isKeyboardSingleUse }),\n ...(shouldHideKeyboardButtons && { shouldHideKeyboardButtons }),\n ...(mtpMessage.viaBotId && { viaBotId: buildApiPeerId(mtpMessage.viaBotId, 'user') }),\n ...(replies?.comments && { threadInfo: buildThreadInfo(replies, mtpMessage.id, chatId) }),\n ...(postAuthor && { adminTitle: postAuthor }),\n ...(mtpMessage.noforwards && { isProtected: true }),\n };\n}\n\nexport function buildMessageReactions(reactions: GramJs.MessageReactions): ApiReactions {\n const {\n recentReactions, results, canSeeList,\n } = reactions;\n\n return {\n canSeeList,\n results: results.map(buildReactionCount),\n recentReactions: recentReactions?.map(buildMessagePeerReaction),\n };\n}\n\nfunction buildReactionCount(reactionCount: GramJs.ReactionCount): ApiReactionCount {\n const { chosen, count, reaction } = reactionCount;\n\n return {\n isChosen: chosen,\n count,\n reaction,\n };\n}\n\nexport function buildMessagePeerReaction(userReaction: GramJs.MessagePeerReaction): ApiUserReaction {\n const { peerId, reaction } = userReaction;\n\n return {\n userId: getApiChatIdFromMtpPeer(peerId),\n reaction,\n };\n}\n\nexport function buildApiAvailableReaction(availableReaction: GramJs.AvailableReaction): ApiAvailableReaction {\n const {\n selectAnimation, staticIcon, reaction, title,\n inactive, aroundAnimation, centerIcon,\n } = availableReaction;\n\n return {\n selectAnimation: buildApiDocument(selectAnimation),\n staticIcon: buildApiDocument(staticIcon),\n aroundAnimation: aroundAnimation ? buildApiDocument(aroundAnimation) : undefined,\n centerIcon: centerIcon ? buildApiDocument(centerIcon) : undefined,\n reaction,\n title,\n isInactive: inactive,\n };\n}\n\nexport function buildMessageContent(\n mtpMessage: UniversalMessage | GramJs.UpdateServiceNotification,\n) {\n let content: ApiMessage['content'] = {};\n\n if (mtpMessage.media) {\n content = {\n ...buildMessageMediaContent(mtpMessage.media),\n };\n }\n\n if (mtpMessage.message && !content.sticker && !content.poll && !content.contact && !(content.video?.isRound)) {\n content = {\n ...content,\n text: buildMessageTextContent(mtpMessage.message, mtpMessage.entities),\n };\n }\n\n return content;\n}\n\nexport function buildMessageTextContent(\n message: string,\n entities?: GramJs.TypeMessageEntity[],\n): ApiFormattedText {\n return {\n text: message,\n ...(entities && { entities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildMessageDraft(draft: GramJs.TypeDraftMessage) {\n if (draft instanceof GramJs.DraftMessageEmpty) {\n return undefined;\n }\n\n const {\n message, entities, replyToMsgId, date,\n } = draft;\n\n return {\n formattedText: message ? buildMessageTextContent(message, entities) : undefined,\n replyingToId: replyToMsgId,\n date,\n };\n}\n\nexport function buildMessageMediaContent(media: GramJs.TypeMessageMedia): ApiMessage['content'] | undefined {\n if ('ttlSeconds' in media && media.ttlSeconds) {\n return undefined;\n }\n\n const sticker = buildSticker(media);\n if (sticker) return { sticker };\n\n const photo = buildPhoto(media);\n if (photo) return { photo };\n\n const video = buildVideo(media);\n if (video) return { video };\n\n const audio = buildAudio(media);\n if (audio) return { audio };\n\n const voice = buildVoice(media);\n if (voice) return { voice };\n\n const document = buildDocumentFromMedia(media);\n if (document) return { document };\n\n const contact = buildContact(media);\n if (contact) return { contact };\n\n const poll = buildPollFromMedia(media);\n if (poll) return { poll };\n\n const webPage = buildWebPage(media);\n if (webPage) return { webPage };\n\n const invoice = buildInvoiceFromMedia(media);\n if (invoice) return { invoice };\n\n const location = buildLocationFromMedia(media);\n if (location) return { location };\n\n 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_WEBM_TYPE && !(self as any).isWebmSupported) {\n return undefined;\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (mimeType === VIDEO_MOV_TYPE && !(self as any).isMovSupported) {\n return undefined;\n }\n\n const videoAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeVideo => a instanceof GramJs.DocumentAttributeVideo);\n\n if (!videoAttr) {\n return undefined;\n }\n\n const gifAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeAnimated => a instanceof GramJs.DocumentAttributeAnimated);\n\n const {\n duration,\n w: width,\n h: height,\n supportsStreaming = false,\n roundMessage: isRound = false,\n } = videoAttr;\n\n return {\n id: String(id),\n mimeType,\n duration,\n fileName: getFilenameFromDocument(document, 'video'),\n width,\n height,\n supportsStreaming,\n isRound,\n isGif: Boolean(gifAttr),\n thumbnail: buildApiThumbnailFromStripped(thumbs),\n size,\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\nfunction buildLocationFromMedia(media: GramJs.TypeMessageMedia): ApiLocation | undefined {\n if (media instanceof GramJs.MessageMediaGeo) {\n return buildGeo(media);\n }\n\n if (media instanceof GramJs.MessageMediaVenue) {\n return buildVenue(media);\n }\n\n if (media instanceof GramJs.MessageMediaGeoLive) {\n return buildGeoLive(media);\n }\n\n return undefined;\n}\n\nfunction buildGeo(media: GramJs.MessageMediaGeo): ApiLocation | undefined {\n const point = buildGeoPoint(media.geo);\n return point && { type: 'geo', geo: point };\n}\n\nfunction buildVenue(media: GramJs.MessageMediaVenue): ApiLocation | undefined {\n const {\n geo, title, provider, address, venueId, venueType,\n } = media;\n const point = buildGeoPoint(geo);\n return point && {\n type: 'venue',\n geo: point,\n title,\n provider,\n address,\n venueId,\n venueType,\n };\n}\n\nfunction buildGeoLive(media: GramJs.MessageMediaGeoLive): ApiLocation | undefined {\n const { geo, period, heading } = media;\n const point = buildGeoPoint(geo);\n return point && {\n type: 'geoLive',\n geo: point,\n period,\n heading,\n };\n}\n\nfunction buildGeoPoint(geo: GramJs.TypeGeoPoint): ApiLocation['geo'] | undefined {\n if (geo instanceof GramJs.GeoPointEmpty) return undefined;\n const {\n long, lat, accuracyRadius, accessHash,\n } = geo;\n return {\n long,\n lat,\n accessHash: accessHash.toString(),\n accuracyRadius,\n };\n}\n\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 ApiExportedInvite,\n ApiChatInviteImporter,\n ApiChatSettings,\n} from '../../types';\nimport { pick, pickTruthy } from '../../../util/iteratees';\nimport {\n buildApiPeerId, getApiChatIdFromMtpPeer, isPeerChat, isPeerUser,\n} from './peers';\nimport { omitVirtualClassFields } from './helpers';\nimport { getServerTime } from '../../../util/serverTime';\n\ntype PeerEntityApiChatFields = Omit;\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 let emoticon: string | undefined;\n if (update.action instanceof GramJs.SendMessageCancelAction) {\n return undefined;\n } else if (update.action instanceof GramJs.SendMessageTypingAction) {\n action = 'lng_user_typing';\n } else if (update.action instanceof GramJs.SendMessageRecordVideoAction) {\n action = 'lng_send_action_record_video';\n } else if (update.action instanceof GramJs.SendMessageUploadVideoAction) {\n action = 'lng_send_action_upload_video';\n } else if (update.action instanceof GramJs.SendMessageRecordAudioAction) {\n action = 'lng_send_action_record_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadAudioAction) {\n action = 'lng_send_action_upload_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadPhotoAction) {\n action = 'lng_send_action_upload_photo';\n } else if (update.action instanceof GramJs.SendMessageUploadDocumentAction) {\n action = 'lng_send_action_upload_file';\n } else if (update.action instanceof GramJs.SendMessageGeoLocationAction) {\n action = 'selecting a location to share';\n } else if (update.action instanceof GramJs.SendMessageChooseContactAction) {\n action = 'selecting a contact to share';\n } else if (update.action instanceof GramJs.SendMessageGamePlayAction) {\n action = 'lng_playing_game';\n } else if (update.action instanceof GramJs.SendMessageRecordRoundAction) {\n action = 'lng_send_action_record_round';\n } else if (update.action instanceof GramJs.SendMessageUploadRoundAction) {\n action = 'lng_send_action_upload_round';\n } else if (update.action instanceof GramJs.SendMessageChooseStickerAction) {\n action = 'lng_send_action_choose_sticker';\n } else if (update.action instanceof GramJs.SpeakingInGroupCallAction) {\n return undefined;\n } else if (update.action instanceof GramJs.SendMessageEmojiInteractionSeen) {\n action = 'lng_user_action_watching_animations';\n emoticon = update.action.emoticon;\n } else if (update.action instanceof GramJs.SendMessageEmojiInteraction) {\n return undefined;\n }\n\n return {\n action,\n ...(emoticon && { emoji: emoticon }),\n ...(!(update instanceof GramJs.UpdateUserTyping) && { userId: getApiChatIdFromMtpPeer(update.fromId) }),\n timestamp: Date.now() + serverTimeOffset * 1000,\n };\n}\n\nexport function buildApiChatFolder(filter: GramJs.DialogFilter): ApiChatFolder {\n return {\n ...pickTruthy(filter, [\n 'id', 'title', 'emoticon', 'contacts', 'nonContacts', 'groups', 'bots',\n 'excludeMuted', 'excludeRead', 'excludeArchived',\n ]),\n channels: filter.broadcasts,\n pinnedChatIds: filter.pinnedPeers.map(getApiChatIdFromMtpPeer).filter(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\nexport function buildApiExportedInvite(invite: GramJs.ChatInviteExported): ApiExportedInvite {\n const {\n revoked,\n date,\n expireDate,\n link,\n permanent,\n startDate,\n usage,\n usageLimit,\n requested,\n requestNeeded,\n title,\n adminId,\n } = invite;\n return {\n isRevoked: revoked,\n date,\n expireDate,\n link,\n isPermanent: permanent,\n startDate,\n usage,\n usageLimit,\n isRequestNeeded: requestNeeded,\n requested,\n title,\n adminId: buildApiPeerId(adminId, 'user'),\n };\n}\n\nexport function buildChatInviteImporter(importer: GramJs.ChatInviteImporter): ApiChatInviteImporter {\n const {\n userId,\n date,\n about,\n requested,\n } = importer;\n return {\n userId: buildApiPeerId(userId, 'user'),\n date,\n about,\n isRequested: requested,\n };\n}\n\nexport function buildApiChatSettings({\n autoarchived,\n reportSpam,\n addContact,\n blockContact,\n}: GramJs.PeerSettings): ApiChatSettings {\n return {\n isAutoArchived: Boolean(autoarchived),\n canReportSpam: Boolean(reportSpam),\n canAddContact: Boolean(addContact),\n canBlockContact: Boolean(blockContact),\n };\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\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 {\n ApiCountry, ApiSession, ApiWallpaper,\n} 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\nexport function buildJson(json: GramJs.TypeJSONValue): any {\n if (json instanceof GramJs.JsonNull) return undefined;\n if (json instanceof GramJs.JsonString\n || json instanceof GramJs.JsonBool\n || json instanceof GramJs.JsonNumber) return json.value;\n if (json instanceof GramJs.JsonArray) return json.value.map(buildJson);\n\n return json.value.reduce((acc: Record, el) => {\n acc[el.key] = buildJson(el.value);\n return acc;\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 buildMessageReactions,\n} from './apiBuilders/messages';\nimport {\n buildChatMember,\n buildChatMembers,\n buildChatTypingStatus,\n buildAvatarHash,\n buildApiChatFromPreview,\n buildApiChatFolder,\n buildApiChatSettings,\n} from './apiBuilders/chats';\nimport { buildApiUser, buildApiUserStatus } from './apiBuilders/users';\nimport {\n buildMessageFromUpdate,\n isMessageWithMedia,\n buildChatPhotoForLocalDb,\n} from './gramjsBuilders';\nimport localDb from './localDb';\nimport { omitVirtualClassFields } from './apiBuilders/helpers';\nimport { DEBUG } from '../../config';\nimport {\n addMessageToLocalDb,\n addEntitiesWithPhotosToLocalDb,\n addPhotoToLocalDb,\n resolveMessageApiChatId,\n serializeBytes,\n} from './helpers';\nimport { buildApiNotifyException, buildPrivacyKey, buildPrivacyRules } from './apiBuilders/misc';\nimport { buildApiPhoto } from './apiBuilders/common';\nimport {\n buildApiGroupCall,\n buildApiGroupCallParticipant,\n getGroupCallId,\n} from './apiBuilders/calls';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './apiBuilders/peers';\nimport { buildApiEmojiInteraction } from './apiBuilders/symbols';\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.MessageActionPaymentSent) {\n onUpdate({\n '@type': 'updatePaymentStateCompleted',\n });\n } else if (action instanceof GramJs.MessageActionChatEditTitle) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n title: action.title,\n },\n });\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n const photo = buildChatPhotoForLocalDb(action.photo);\n const avatarHash = buildAvatarHash(photo);\n\n const localDbChatId = resolveMessageApiChatId(update.message)!;\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = photo;\n }\n addPhotoToLocalDb(action.photo);\n\n if (avatarHash) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n avatarHash,\n },\n ...(action.photo instanceof GramJs.Photo && { newProfilePhoto: buildApiPhoto(action.photo) }),\n });\n }\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n const localDbChatId = resolveMessageApiChatId(update.message)!;\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = new GramJs.ChatPhotoEmpty();\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: { avatarHash: undefined },\n });\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && Boolean(e.self) && e.id === action.userId\n ))) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n 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 && Boolean(e.self) && action.users.includes(e.id)\n ))) {\n onUpdate({\n '@type': 'updateChatJoin',\n id: message.chatId,\n });\n }\n } else if (action instanceof GramJs.MessageActionGroupCall) {\n if (!action.duration && action.call) {\n onUpdate({\n '@type': 'updateGroupCallChatId',\n chatId: message.chatId,\n call: {\n id: action.call.id.toString(),\n accessHash: action.call.accessHash.toString(),\n },\n });\n }\n }\n }\n } else if (\n update instanceof GramJs.UpdateEditMessage\n || update instanceof GramJs.UpdateEditChannelMessage\n ) {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n const message = buildApiMessage(update.message)!;\n\n onUpdate({\n '@type': 'updateMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else if (update instanceof GramJs.UpdateMessageReactions) {\n onUpdate({\n '@type': 'updateMessageReactions',\n id: update.msgId,\n chatId: getApiChatIdFromMtpPeer(update.peer),\n reactions: buildMessageReactions(update.reactions),\n });\n } else if (update instanceof GramJs.UpdateDeleteMessages) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: update.messages,\n });\n } else if (update instanceof GramJs.UpdateDeleteScheduledMessages) {\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: update.messages,\n chatId: getApiChatIdFromMtpPeer(update.peer),\n });\n } else if (update instanceof GramJs.UpdateDeleteChannelMessages) {\n const chatId = buildApiPeerId(update.channelId, 'channel');\n const ids = update.messages;\n const existingIds = ids.filter((id) => localDb.messages[`${chatId}-${id}`]);\n const missingIds = ids.filter((id) => !localDb.messages[`${chatId}-${id}`]);\n const profilePhotoIds = ids.map((id) => {\n const message = localDb.messages[`${chatId}-${id}`];\n\n return message && message instanceof GramJs.MessageService && 'photo' in message.action\n ? String(message.action.photo.id)\n : undefined;\n }).filter(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 if (update.action instanceof GramJs.SendMessageEmojiInteraction) {\n onUpdate({\n '@type': 'updateStartEmojiInteraction',\n id,\n emoji: update.action.emoticon,\n messageId: update.action.msgId,\n interaction: buildApiEmojiInteraction(JSON.parse(update.action.interaction.data)),\n });\n } else {\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update, serverTimeOffset),\n });\n }\n } else if (update instanceof GramJs.UpdateChannelUserTyping) {\n const id = buildApiPeerId(update.channelId, 'channel');\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update, serverTimeOffset),\n });\n } else if (update instanceof GramJs.UpdateChannel) {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n const channel = _entities.find((e): e is GramJs.Channel | GramJs.ChannelForbidden => (\n e instanceof GramJs.Channel || e instanceof GramJs.ChannelForbidden\n ));\n\n if (channel instanceof GramJs.Channel) {\n if (shouldIgnoreNextChannelUpdate) {\n shouldIgnoreNextChannelUpdate = false;\n return;\n }\n\n if (originRequest instanceof GramJs.messages.ToggleNoForwards) {\n shouldIgnoreNextChannelUpdate = true;\n setTimeout(() => { shouldIgnoreNextChannelUpdate = false; }, IGNORE_NEXT_CHANNEL_UPDATE_TIMEOUT);\n }\n\n const chat = buildApiChatFromPreview(channel);\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n onUpdate({\n '@type': chat.isNotJoined ? 'updateChatLeave' : 'updateChatJoin',\n id: buildApiPeerId(update.channelId, 'channel'),\n });\n }\n } else if (channel instanceof GramJs.ChannelForbidden) {\n const chatId = buildApiPeerId(update.channelId, 'channel');\n\n onUpdate({\n '@type': 'updateChat',\n id: chatId,\n chat: {\n isRestricted: true,\n },\n });\n\n onUpdate({\n '@type': 'updateChatLeave',\n id: chatId,\n });\n } else if (_entities.length === 0) {\n // The link to the discussion group may have been changed.\n // No corresponding update available at this moment https://core.telegram.org/type/Updates\n onUpdate({\n '@type': 'resetMessages',\n id: buildApiPeerId(update.channelId, 'channel'),\n });\n }\n } else if (\n update instanceof GramJs.UpdateDialogUnreadMark\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n chat: {\n hasUnreadMark: update.unread,\n },\n });\n } else if (update instanceof GramJs.UpdateChatDefaultBannedRights) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n defaultBannedRights: omitVirtualClassFields(update.defaultBannedRights),\n },\n });\n\n // Users\n } else if (update instanceof GramJs.UpdateUserStatus) {\n onUpdate({\n '@type': 'updateUserStatus',\n userId: buildApiPeerId(update.userId, 'user'),\n status: buildApiUserStatus(update.status),\n });\n } else if (update instanceof GramJs.UpdateUserName) {\n const apiUserId = buildApiPeerId(update.userId, 'user');\n const updatedUser = localDb.users[apiUserId];\n const user = updatedUser?.mutualContact && !updatedUser.self\n ? pick(update, ['username'])\n : pick(update, ['firstName', 'lastName', 'username']);\n\n onUpdate({\n '@type': 'updateUser',\n id: apiUserId,\n user,\n });\n } else if (update instanceof GramJs.UpdateUserPhoto) {\n const { userId, photo } = update;\n const apiUserId = buildApiPeerId(userId, 'user');\n const avatarHash = buildAvatarHash(photo);\n\n if (localDb.users[apiUserId]) {\n localDb.users[apiUserId].photo = photo;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: apiUserId,\n user: { avatarHash },\n });\n } else if (update instanceof GramJs.UpdateUserPhone) {\n const { userId, phone } = update;\n\n onUpdate({\n '@type': 'updateUser',\n id: buildApiPeerId(userId, 'user'),\n user: { phoneNumber: phone },\n });\n } else if (update instanceof GramJs.UpdatePeerSettings) {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { _entities, settings } = update;\n if (!_entities) {\n return;\n }\n\n if (_entities?.length) {\n _entities\n .filter((e) => e instanceof GramJs.User && !e.contact)\n .forEach((user) => {\n onUpdate({\n '@type': 'deleteContact',\n id: buildApiPeerId(user.id, 'user'),\n });\n });\n\n _entities\n .filter((e) => e instanceof GramJs.User && e.contact)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user: {\n ...user,\n ...(settings && { settings: buildApiChatSettings(settings) }),\n },\n });\n });\n }\n\n // Settings\n } else if (update instanceof GramJs.UpdateNotifySettings) {\n const {\n notifySettings: {\n showPreviews, silent, muteUntil,\n },\n peer: { className },\n } = update;\n\n const peerType = className === 'NotifyUsers'\n ? 'contact'\n : (className === 'NotifyChats'\n ? 'group'\n : (className === 'NotifyBroadcasts'\n ? 'broadcast'\n : undefined\n )\n );\n\n if (!peerType) {\n return;\n }\n\n onUpdate({\n '@type': 'updateNotifySettings',\n peerType,\n isSilent: Boolean(silent\n || (typeof muteUntil === 'number' && Date.now() + serverTimeOffset * 1000 < muteUntil * 1000)),\n shouldShowPreviews: Boolean(showPreviews),\n });\n } else if (update instanceof GramJs.UpdatePeerBlocked) {\n onUpdate({\n '@type': 'updatePeerBlocked',\n id: getApiChatIdFromMtpPeer(update.peerId),\n isBlocked: update.blocked,\n });\n } else if (update instanceof GramJs.UpdatePrivacy) {\n const key = buildPrivacyKey(update.key);\n if (key) {\n onUpdate({\n '@type': 'updatePrivacy',\n key,\n rules: buildPrivacyRules(update.rules),\n });\n }\n\n // Misc\n } else if (update instanceof GramJs.UpdateDraftMessage) {\n onUpdate({\n '@type': 'draftMessage',\n chatId: getApiChatIdFromMtpPeer(update.peer),\n ...buildMessageDraft(update.draft),\n });\n } else if (update instanceof GramJs.UpdateContactsReset) {\n onUpdate({ '@type': 'updateResetContactList' });\n } else if (update instanceof GramJs.UpdateFavedStickers) {\n onUpdate({ '@type': 'updateFavoriteStickers' });\n } else if (update instanceof GramJs.UpdateGroupCall) {\n onUpdate({\n '@type': 'updateGroupCall',\n call: buildApiGroupCall(update.call),\n });\n } else if (update instanceof GramJs.UpdateGroupCallConnection) {\n onUpdate({\n '@type': 'updateGroupCallConnection',\n data: JSON.parse(update.params.data) as GroupCallConnectionData,\n presentation: Boolean(update.presentation),\n });\n } else if (update instanceof GramJs.UpdateGroupCallParticipants) {\n // eslint-disable-next-line no-underscore-dangle\n const entities = update._entities;\n if (entities) {\n addEntitiesWithPhotosToLocalDb(entities);\n dispatchUserAndChatUpdates(entities);\n }\n\n onUpdate({\n '@type': 'updateGroupCallParticipants',\n groupCallId: getGroupCallId(update.call),\n participants: update.participants.map(buildApiGroupCallParticipant),\n });\n } else if (update instanceof GramJs.UpdatePendingJoinRequests) {\n // eslint-disable-next-line no-underscore-dangle\n const entities = update._entities;\n if (entities) {\n addEntitiesWithPhotosToLocalDb(entities);\n dispatchUserAndChatUpdates(entities);\n }\n\n onUpdate({\n '@type': 'updatePendingJoinRequests',\n chatId: getApiChatIdFromMtpPeer(update.peer),\n recentRequesterIds: update.recentRequesters.map((id) => buildApiPeerId(id, 'user')),\n requestsPending: update.requestsPending,\n });\n } else if (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 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 { 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 'document'\n);\n\nconst MEDIA_ENTITY_TYPES = new Set(['msg', 'sticker', 'gif', 'wallpaper', 'photo', 'webDocument', 'document']);\nconst TGS_MIME_TYPE = 'application/x-tgsticker';\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 as string | Blob);\n const arrayBuffer = mediaFormat === ApiMediaFormat.Progressive ? parsed as ArrayBuffer : undefined;\n\n return {\n prepared,\n arrayBuffer,\n mimeType,\n fullSize,\n };\n}\n\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('staticMap')\n ? url.match(/(staticMap):([0-9-]+)(\\?.+)/)\n : url.startsWith('webDocument')\n ? url.match(/(webDocument):(.+)/)\n : url.match(\n /(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file|document)([-\\d\\w./]+)(?::\\d+)?(\\?size=\\w+)?/,\n );\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] === 'staticMap') {\n const accessHash = mediaMatch[2];\n const params = mediaMatch[3];\n const parsedParams = new URLSearchParams(params);\n const long = parsedParams.get('long');\n const lat = parsedParams.get('lat');\n const w = parsedParams.get('w');\n const h = parsedParams.get('h');\n const zoom = parsedParams.get('zoom');\n const scale = parsedParams.get('scale');\n const accuracyRadius = parsedParams.get('accuracy_radius');\n\n const data = await client.downloadStaticMap(accessHash, long, lat, w, h, zoom, scale, accuracyRadius);\n return {\n mimeType: 'image/png',\n data,\n };\n }\n\n if (mediaMatch[1] === 'avatar' || mediaMatch[1] === 'profile') {\n entityType = getEntityTypeById(entityId);\n } else {\n entityType = mediaMatch[1] as (\n 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'stickerSet' | 'photo' | 'webDocument' | 'document'\n );\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 case 'document':\n entity = localDb.documents[entityId];\n break;\n }\n\n if (!entity) {\n return undefined;\n }\n\n if (MEDIA_ENTITY_TYPES.has(entityType)) {\n if (mediaFormat === ApiMediaFormat.Stream) {\n onProgress!.acceptsBuffer = true;\n }\n\n const data = await client.downloadMedia(entity, {\n sizeType, start, end, progressCallback: onProgress, workers: DOWNLOAD_WORKERS,\n });\n let mimeType;\n let fullSize;\n\n if (entity instanceof GramJs.Message) {\n mimeType = getMessageMediaMimeType(entity, sizeType);\n if (entity.media instanceof GramJs.MessageMediaDocument && entity.media.document instanceof GramJs.Document) {\n fullSize = entity.media.document.size;\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 ? TGS_MIME_TYPE : 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.MessageMediaGeo\n || message.media instanceof GramJs.MessageMediaVenue\n || message.media instanceof GramJs.MessageMediaGeoLive) {\n return 'image/png';\n }\n\n if (message.media instanceof GramJs.MessageMediaDocument && message.media.document instanceof GramJs.Document) {\n if (sizeType) {\n return message.media.document!.attributes.some((a) => a instanceof GramJs.DocumentAttributeSticker)\n ? 'image/webp'\n : 'image/jpeg';\n }\n\n return message.media.document!.mimeType;\n }\n\n if (message.media instanceof GramJs.MessageMediaWebPage\n && message.media.webpage instanceof GramJs.WebPage\n && message.media.webpage.document instanceof GramJs.Document) {\n if (sizeType) {\n return 'image/jpeg';\n }\n\n return message.media.webpage.document.mimeType;\n }\n\n return undefined;\n}\n\n// eslint-disable-next-line no-async-without-await/no-async-without-await\nasync function parseMedia(\n data: Buffer, mediaFormat: ApiMediaFormat, mimeType?: string,\n): Promise {\n switch (mediaFormat) {\n case ApiMediaFormat.BlobUrl:\n case ApiMediaFormat.Lottie: {\n return new Blob([data], { type: mimeType });\n }\n case ApiMediaFormat.Progressive: {\n return data.buffer;\n }\n }\n\n return undefined;\n}\n\nfunction prepareMedia(mediaData: Exclude): 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, isWebmSupported,\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 // eslint-disable-next-line no-restricted-globals\n (self as any).isWebmSupported = isWebmSupported;\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: any) {\n // eslint-disable-next-line no-console\n console.error(err);\n\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 shouldReturnTrue: true,\n shouldThrow?: boolean,\n shouldIgnoreUpdates?: undefined,\n dcId?: number,\n): Promise;\n\nexport async function invokeRequest(\n request: T,\n shouldReturnTrue?: boolean,\n shouldThrow?: boolean,\n shouldIgnoreUpdates?: boolean,\n dcId?: number,\n): Promise;\n\nexport async function invokeRequest(\n request: T,\n shouldReturnTrue = false,\n shouldThrow = false,\n shouldIgnoreUpdates = false,\n dcId?: number,\n) {\n if (!isConnected) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(`[GramJs/client] INVOKE ERROR ${request.className}: Client is not connected`);\n }\n\n return undefined;\n }\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ${request.className}`);\n }\n\n const result = await client.invoke(request, dcId);\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE RESPONSE ${request.className}`, result);\n }\n\n if (!shouldIgnoreUpdates) {\n handleUpdatesFromRequest(request, result);\n }\n\n return shouldReturnTrue ? result && true : result;\n } catch (err: any) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ERROR ${request.className}`);\n // eslint-disable-next-line no-console\n console.error(err);\n }\n\n if (shouldThrow) {\n throw err;\n }\n\n dispatchErrorUpdate(err, request);\n\n return undefined;\n }\n}\n\nfunction handleUpdatesFromRequest(request: T, result: T['__response']) {\n let manyUpdates;\n let singleUpdate;\n\n if (result instanceof GramJs.UpdatesCombined || result instanceof GramJs.Updates) {\n manyUpdates = result;\n } else if (typeof result === 'object' && 'updates' in result && (\n result.updates instanceof GramJs.Updates || result.updates instanceof GramJs.UpdatesCombined\n )) {\n manyUpdates = result.updates;\n } else if (\n result instanceof GramJs.UpdateShortMessage\n || result instanceof GramJs.UpdateShortChatMessage\n || result instanceof GramJs.UpdateShort\n || result instanceof GramJs.UpdateShortSentMessage\n ) {\n singleUpdate = result;\n }\n\n if (manyUpdates) {\n injectUpdateEntities(manyUpdates);\n\n manyUpdates.updates.forEach((update) => {\n updater(update, request);\n });\n } else if (singleUpdate) {\n updater(singleUpdate, request);\n }\n}\n\nexport function downloadMedia(\n args: { url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number; isHtmlAllowed?: boolean },\n onProgress?: ApiOnProgress,\n) {\n return downloadMediaWithClient(args, client, isConnected, onProgress);\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: any) {\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 buildApiChatSettings,\n} from '../apiBuilders/chats';\nimport { buildApiMessage, buildMessageDraft } from '../apiBuilders/messages';\nimport { buildApiUser, buildApiUsersAndStatuses } from '../apiBuilders/users';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n buildInputEntity,\n buildInputPeer,\n buildMtpMessageEntity,\n buildFilterFromApiFolder,\n isMessageWithMedia,\n buildChatBannedRights,\n buildChatAdminRights,\n} from '../gramjsBuilders';\nimport { addEntitiesWithPhotosToLocalDb, addMessageToLocalDb, addPhotoToLocalDb } from '../helpers';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\nimport { buildApiPhoto } from '../apiBuilders/common';\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 fetchChatSettings(chat: ApiChat) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPeerSettings({\n peer: buildInputPeer(id, accessHash),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return buildApiChatSettings(result.settings);\n}\n\nexport async function searchChats({ query }: { query: string }) {\n const result = await invokeRequest(new GramJs.contacts.Search({ q: query }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const localPeerIds = result.myResults.map(getApiChatIdFromMtpPeer);\n const allChats = result.chats.concat(result.users)\n .map((user) => buildApiChatFromPreview(user))\n .filter(Boolean as any);\n const allUsers = result.users.map(buildApiUser).filter((user) => Boolean(user) && !user.isSelf) as ApiUser[];\n\n return {\n localChats: allChats.filter((r) => localPeerIds.includes(r.id)),\n localUsers: allUsers.filter((u) => localPeerIds.includes(u.id)),\n globalChats: allChats.filter((r) => !localPeerIds.includes(r.id)),\n globalUsers: allUsers.filter((u) => !localPeerIds.includes(u.id)),\n };\n}\n\nexport async function fetchChat({\n type, user,\n}: {\n type: 'user' | 'self' | 'support'; user?: ApiUser;\n}) {\n let mtpUser: GramJs.User | undefined;\n\n if (type === 'self' || type === 'user') {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: [\n type === 'user' && user\n ? buildInputEntity(user.id, user.accessHash) as GramJs.InputUser\n : new GramJs.InputUserSelf(),\n ],\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n [mtpUser] = result;\n } else if (type === 'support') {\n const result = await invokeRequest(new GramJs.help.GetSupport());\n if (!result || !result.user) {\n return undefined;\n }\n\n mtpUser = result.user;\n }\n\n const chat = buildApiChatFromPreview(mtpUser!, type === 'support');\n if (!chat) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n return { chatId: chat.id };\n}\n\nexport async function requestChatUpdate({\n chat,\n serverTimeOffset,\n lastLocalMessage,\n noLastMessage,\n}: {\n chat: ApiChat; serverTimeOffset: number; lastLocalMessage?: ApiMessage; noLastMessage?: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPeerDialogs({\n peers: [new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n })],\n }));\n\n if (!result) {\n return;\n }\n\n const dialog = result.dialogs[0];\n if (!dialog || !(dialog instanceof GramJs.Dialog)) {\n return;\n }\n\n const peersByKey = preparePeers(result);\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n if (!peerEntity) {\n return;\n }\n\n updateLocalDb(result);\n\n const lastRemoteMessage = buildApiMessage(result.messages[0]);\n const lastMessage = lastLocalMessage && (!lastRemoteMessage || (lastLocalMessage.date > lastRemoteMessage.date))\n ? lastLocalMessage\n : lastRemoteMessage;\n\n onUpdate({\n '@type': 'updateChat',\n id,\n chat: {\n ...buildApiChatFromDialog(dialog, peerEntity, serverTimeOffset),\n ...(!noLastMessage && { lastMessage }),\n },\n });\n}\n\nexport function saveDraft({\n chat,\n text,\n entities,\n replyToMsgId,\n}: {\n chat: ApiChat;\n text: string;\n entities?: ApiMessageEntity[];\n replyToMsgId?: number;\n}) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: text,\n ...(entities && {\n entities: entities.map(buildMtpMessageEntity),\n }),\n replyToMsgId,\n }));\n}\n\nexport function clearDraft(chat: ApiChat) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: '',\n }));\n}\n\nasync function getFullChatInfo(chatId: string): Promise<{\n fullInfo: ApiChatFullInfo;\n users?: ApiUser[];\n groupCall?: Partial;\n membersCount?: number;\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 availableReactions,\n recentRequesters,\n requestsPending,\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 enabledReactions: availableReactions,\n requestsPending,\n recentRequesterIds: recentRequesters?.map((userId) => buildApiPeerId(userId, 'user')),\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 membersCount: members?.length,\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 membersCount?: number;\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 canViewStats,\n linkedChatId,\n hiddenPrehistory,\n call,\n botInfo,\n availableReactions,\n defaultSendAs,\n requestsPending,\n recentRequesters,\n statsDc,\n participantsCount,\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 canViewStatistics: canViewStats,\n isPreHistoryHidden: hiddenPrehistory,\n members,\n kickedMembers,\n adminMembers,\n groupCallId: call ? String(call.id) : undefined,\n linkedChatId: linkedChatId ? buildApiPeerId(linkedChatId, 'chat') : undefined,\n botCommands,\n enabledReactions: availableReactions,\n sendAsId: defaultSendAs ? getApiChatIdFromMtpPeer(defaultSendAs) : undefined,\n requestsPending,\n recentRequesterIds: recentRequesters?.map((userId) => buildApiPeerId(userId, 'user')),\n statisticsDcId: statsDc,\n },\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 membersCount: participantsCount,\n };\n}\n\nexport async function updateChatMutedState({\n chat, isMuted, serverTimeOffset,\n}: {\n chat: ApiChat; isMuted: boolean; serverTimeOffset: number;\n}) {\n await invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer: new GramJs.InputNotifyPeer({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }),\n settings: new GramJs.InputPeerNotifySettings({ muteUntil: isMuted ? MAX_INT_32 : 0 }),\n }));\n\n onUpdate({\n '@type': 'updateNotifyExceptions',\n chatId: chat.id,\n isMuted,\n });\n\n void requestChatUpdate({\n chat,\n serverTimeOffset,\n noLastMessage: true,\n });\n}\n\nexport async function createChannel({\n title, about = '', users,\n}: {\n title: string; about?: string; users?: ApiUser[];\n}, noErrorUpdate = false): Promise {\n const result = await invokeRequest(new GramJs.channels.CreateChannel({\n broadcast: true,\n title,\n about,\n }));\n\n // `createChannel` can return a lot of different update types according to docs,\n // but currently channel creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n return undefined;\n }\n\n const newChannel = result.chats[0];\n if (!newChannel || !(newChannel instanceof GramJs.Channel)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created channel not found', result);\n }\n return undefined;\n }\n\n const channel = buildApiChatFromPreview(newChannel)!;\n\n if (users?.length) {\n try {\n await invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(channel.id, channel.accessHash) as GramJs.InputChannel,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }), undefined, noErrorUpdate);\n } catch (err) {\n // `noErrorUpdate` will cause an exception which we don't want either\n }\n }\n\n return channel;\n}\n\nexport function joinChannel({\n channelId, accessHash,\n}: {\n channelId: string; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.JoinChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\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 }), undefined, true);\n\n // `createChat` can return a lot of different update types according to docs,\n // but currently chat creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected chat creation update', result);\n }\n return undefined;\n }\n\n const newChat = result.chats[0];\n if (!newChat || !(newChat instanceof GramJs.Chat)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created chat not found', result);\n }\n return undefined;\n }\n\n return buildApiChatFromPreview(newChat);\n}\n\nexport async function editChatPhoto({\n chatId, accessHash, photo,\n}: {\n chatId: string; accessHash?: string; photo: File;\n}) {\n const uploadedPhoto = await uploadFile(photo);\n const inputEntity = buildInputEntity(chatId, accessHash);\n\n return invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditPhoto({\n channel: inputEntity as GramJs.InputChannel,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n })\n : new GramJs.messages.EditChatPhoto({\n chatId: inputEntity as BigInt.BigInteger,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n }),\n true,\n );\n}\n\nexport async function toggleChatPinned({\n chat,\n shouldBePinned,\n}: {\n chat: ApiChat;\n shouldBePinned: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.ToggleDialogPin({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n pinned: shouldBePinned || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: chat.id,\n isPinned: shouldBePinned,\n });\n }\n}\n\nexport function toggleChatArchived({\n chat, folderId,\n}: {\n chat: ApiChat; folderId: number;\n}) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.folders.EditPeerFolders({\n folderPeers: [new GramJs.InputFolderPeer({\n peer: buildInputPeer(id, accessHash),\n folderId,\n })],\n }), true);\n}\n\nexport async function fetchChatFolders() {\n const result = await invokeRequest(new GramJs.messages.GetDialogFilters());\n\n if (!result) {\n return undefined;\n }\n\n 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 getChatByPhoneNumber(phoneNumber: string) {\n const result = await invokeRequest(new GramJs.contacts.ResolvePhone({\n phone: phoneNumber,\n }));\n\n return processResolvedPeer(result);\n}\n\nexport async function getChatByUsername(username: string) {\n const result = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username,\n }));\n\n return processResolvedPeer(result);\n}\n\nfunction processResolvedPeer(result?: GramJs.contacts.TypeResolvedPeer) {\n if (!result) {\n return undefined;\n }\n\n const { users, chats } = result;\n\n const chat = chats.length\n ? buildApiChatFromPreview(chats[0])\n : buildApiChatFromPreview(users[0]);\n\n if (!chat) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return chat;\n}\n\nexport function togglePreHistoryHidden({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.TogglePreHistoryHidden({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\nexport function updateChatDefaultBannedRights({\n chat, bannedRights,\n}: { chat: ApiChat; bannedRights: ApiChatBannedRights }) {\n const { id, accessHash } = chat;\n const peer = buildInputPeer(id, accessHash);\n\n return invokeRequest(new GramJs.messages.EditChatDefaultBannedRights({\n peer,\n bannedRights: buildChatBannedRights(bannedRights),\n }), true);\n}\n\nexport function updateChatMemberBannedRights({\n chat, user, bannedRights, untilDate,\n}: { chat: ApiChat; user: ApiUser; bannedRights: ApiChatBannedRights; untilDate?: number }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const participant = buildInputPeer(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditBanned({\n channel,\n participant,\n bannedRights: buildChatBannedRights(bannedRights, untilDate),\n }), true);\n}\n\nexport function updateChatAdmin({\n chat, user, adminRights, customTitle = '',\n}: { chat: ApiChat; user: ApiUser; adminRights: ApiChatAdminRights; customTitle: string }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const userId = buildInputEntity(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditAdmin({\n channel,\n userId,\n adminRights: buildChatAdminRights(adminRights),\n rank: customTitle,\n }), true);\n}\n\nexport async function updateChatTitle(chat: ApiChat, title: string) {\n const inputEntity = buildInputEntity(chat.id, chat.accessHash);\n await invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditTitle({\n channel: inputEntity as GramJs.InputChannel,\n title,\n }) : new GramJs.messages.EditChatTitle({\n chatId: inputEntity as BigInt.BigInteger,\n title,\n }),\n true,\n );\n}\n\nexport async function updateChatAbout(chat: ApiChat, about: string) {\n const result = await invokeRequest(new GramJs.messages.EditChatAbout({\n peer: buildInputPeer(chat.id, chat.accessHash),\n about,\n }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n about,\n },\n });\n}\n\nexport function toggleSignatures({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.ToggleSignatures({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\ntype ChannelMembersFilter =\n 'kicked'\n | 'admin'\n | 'recent';\n\nexport async function fetchMembers(\n chatId: string,\n accessHash: string,\n memberFilter: ChannelMembersFilter = 'recent',\n offset?: number,\n) {\n let filter: GramJs.TypeChannelParticipantsFilter;\n\n switch (memberFilter) {\n case 'kicked':\n filter = new GramJs.ChannelParticipantsKicked({ q: '' });\n break;\n case 'admin':\n filter = new GramJs.ChannelParticipantsAdmins();\n break;\n default:\n filter = new GramJs.ChannelParticipantsRecent();\n break;\n }\n\n const result = await invokeRequest(new GramJs.channels.GetParticipants({\n channel: buildInputEntity(chatId, accessHash) as GramJs.InputChannel,\n filter,\n offset,\n limit: MEMBERS_LOAD_SLICE,\n }));\n\n if (!result || result instanceof GramJs.channels.ChannelParticipantsNotModified) {\n return undefined;\n }\n\n updateLocalDb(result);\n\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 }), true);\n}\n\nexport async function migrateChat(chat: ApiChat) {\n const result = await invokeRequest(\n new GramJs.messages.MigrateChat({ chatId: buildInputEntity(chat.id) as BigInt.BigInteger }),\n );\n\n // `migrateChat` can return a lot of different update types according to docs,\n // but currently chat migrations returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!result || !(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildApiChatFromPreview(result.chats[1]);\n}\n\nexport async function openChatByInvite(hash: string) {\n const result = await invokeRequest(new GramJs.messages.CheckChatInvite({ hash }));\n\n if (!result) {\n return undefined;\n }\n\n let chat: ApiChat | undefined;\n\n if (result instanceof GramJs.ChatInvite) {\n const {\n photo, participantsCount, title, channel, requestNeeded, about, megagroup,\n } = result;\n\n if (photo instanceof GramJs.Photo) {\n addPhotoToLocalDb(result.photo);\n }\n\n onUpdate({\n '@type': 'showInvite',\n data: {\n title,\n about,\n hash,\n participantsCount,\n isChannel: channel && !megagroup,\n isRequestNeeded: requestNeeded,\n ...(photo instanceof GramJs.Photo && { photo: buildApiPhoto(photo) }),\n },\n });\n } else {\n chat = buildApiChatFromPreview(result.chat);\n\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n }\n }\n\n if (!chat) {\n return undefined;\n }\n\n return { chatId: chat.id };\n}\n\nexport async function addChatMembers(chat: ApiChat, users: ApiUser[], noErrorUpdate = false) {\n try {\n if (chat.type === 'chatTypeChannel' || chat.type === 'chatTypeSuperGroup') {\n return await invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n users: users.map((user) => buildInputEntity(user.id, user.accessHash)) as GramJs.InputUser[],\n }), true, noErrorUpdate);\n }\n\n return await Promise.all(users.map((user) => {\n return invokeRequest(new GramJs.messages.AddChatUser({\n chatId: buildInputEntity(chat.id) as BigInt.BigInteger,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true, noErrorUpdate);\n }));\n } catch (err) {\n // `noErrorUpdate` will cause an exception which we don't want either\n return undefined;\n }\n}\n\nexport function deleteChatMember(chat: ApiChat, user: ApiUser) {\n if (chat.type === 'chatTypeChannel' || chat.type === 'chatTypeSuperGroup') {\n return updateChatMemberBannedRights({\n chat,\n user,\n bannedRights: {\n viewMessages: true,\n sendMessages: true,\n sendMedia: true,\n sendStickers: true,\n sendGifs: true,\n sendGames: true,\n sendInline: true,\n embedLinks: true,\n sendPolls: true,\n changeInfo: true,\n inviteUsers: true,\n pinMessages: true,\n },\n untilDate: MAX_INT_32,\n });\n } else {\n return invokeRequest(new GramJs.messages.DeleteChatUser({\n chatId: buildInputEntity(chat.id) as BigInt.BigInteger,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true);\n }\n}\n\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 }));\n if (!(updates instanceof GramJs.Updates) || !updates.chats.length) {\n return undefined;\n }\n\n return buildApiChatFromPreview(updates.chats[0]);\n}\n\nexport function setChatEnabledReactions({\n chat, enabledReactions,\n}: {\n chat: ApiChat; enabledReactions: string[];\n}) {\n return invokeRequest(new GramJs.messages.SetChatAvailableReactions({\n peer: buildInputPeer(chat.id, chat.accessHash),\n availableReactions: enabledReactions,\n }), true);\n}\n\nexport function toggleIsProtected({\n chat, isProtected,\n}: { chat: ApiChat; isProtected: boolean }) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.messages.ToggleNoForwards({\n peer: buildInputPeer(id, accessHash),\n enabled: isProtected,\n }), true);\n}\n","import { pause } from './schedulers';\n\n// Polyfill for Safari: `File` is not available in web worker\nif (typeof File === 'undefined') {\n // eslint-disable-next-line no-global-assign, no-restricted-globals, func-names\n self.File = class extends Blob {\n name: string;\n\n constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag) {\n if (options) {\n const { type, ...rest } = options;\n super(fileBits, { type });\n Object.assign(this, rest);\n } else {\n super(fileBits);\n }\n\n this.name = fileName;\n }\n } as typeof File;\n}\n\nexport function dataUriToBlob(dataUri: string) {\n const arr = dataUri.split(',');\n const mime = arr[0].match(/:(.*?);/)![1];\n const bstr = atob(arr[1]);\n let n = bstr.length;\n const u8arr = new Uint8Array(n);\n\n while (n--) {\n u8arr[n] = bstr.charCodeAt(n);\n }\n\n return new Blob([u8arr], { type: mime });\n}\n\nexport function blobToDataUri(blob: Blob): Promise {\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 ApiAttachment,\n ApiChat,\n ApiGlobalMessageSearchType,\n ApiMessage,\n ApiMessageEntity,\n ApiMessageSearchType,\n ApiNewPoll,\n ApiOnProgress,\n ApiReportReason,\n ApiSticker,\n ApiThreadInfo,\n ApiUser,\n ApiVideo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n OnApiUpdate,\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 buildLocalForwardedMessage,\n buildLocalMessage,\n buildWebPage,\n buildApiSponsoredMessage,\n} from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport {\n buildInputEntity,\n buildInputMediaDocument,\n buildInputPeer,\n buildInputPoll,\n buildInputReportReason,\n buildMtpMessageEntity,\n generateRandomBigInt,\n getEntityTypeById,\n isMessageWithMedia,\n isServiceMessageWithMedia,\n buildSendMessageAction,\n} from '../gramjsBuilders';\nimport localDb from '../localDb';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { fetchFile } from '../../../util/files';\nimport {\n addEntitiesWithPhotosToLocalDb,\n addMessageToLocalDb,\n deserializeBytes,\n resolveMessageApiChatId,\n} from '../helpers';\nimport { interpolateArray } from '../../../util/waveform';\nimport { requestChatUpdate } from './chats';\nimport { getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\n\nconst FAST_SEND_TIMEOUT = 1000;\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchMessages({\n chat,\n threadId,\n ...pagination\n}: {\n chat: ApiChat;\n threadId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n}) {\n const RequestClass = threadId === MAIN_THREAD_ID ? GramJs.messages.GetHistory : GramJs.messages.GetReplies;\n let result;\n\n try {\n result = await invokeRequest(new RequestClass({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(threadId !== MAIN_THREAD_ID && {\n msgId: threadId,\n }),\n ...pagination,\n }), undefined, true);\n } catch (err: any) {\n if (err.message === 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: {\n isRestricted: true,\n },\n });\n }\n }\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(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: any) {\n const { message } = err;\n\n // When fetching messages for the bot @replies, there may be situations when the user was banned\n // in the comment group or this group was deleted\n if (message !== 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'error',\n error: {\n message,\n isSlowMode: false,\n hasErrorKey: true,\n },\n });\n }\n }\n\n if (!result || result instanceof GramJs.messages.MessagesNotModified) {\n return undefined;\n }\n\n const mtpMessage = result.messages[0];\n if (!mtpMessage) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.MessageEmpty) {\n return MESSAGE_DELETED;\n }\n\n const message = mtpMessage && buildApiMessage(mtpMessage);\n if (!message) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.Message) {\n addMessageToLocalDb(mtpMessage);\n }\n\n const users = result.users.map(buildApiUser).filter(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,\n text,\n entities,\n replyingTo,\n attachment,\n sticker,\n gif,\n poll,\n contact,\n groupedId,\n scheduledAt,\n sendAs,\n serverTimeOffset,\n );\n onUpdate({\n '@type': localMessage.isScheduled ? 'newScheduledMessage' : 'newMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: localMessage,\n });\n\n // This is expected to arrive after `updateMessageSendSucceeded` which replaces the local ID,\n // so in most cases this will be simply ignored\n setTimeout(() => {\n onUpdate({\n '@type': localMessage.isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: {\n sendingState: 'messageSendingStatePending',\n },\n });\n }, FAST_SEND_TIMEOUT);\n\n const randomId = generateRandomBigInt();\n localDb.localMessages[String(randomId)] = localMessage;\n\n if (groupedId) {\n return sendGroupedMedia({\n chat, text, entities, replyingTo, attachment: attachment!, groupedId, isSilent, scheduledAt,\n }, randomId, localMessage, onProgress);\n }\n\n const prevQueue = queue;\n queue = (async () => {\n let media: GramJs.TypeInputMedia | undefined;\n if (attachment) {\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n await prevQueue;\n\n return;\n }\n } else if (sticker) {\n media = buildInputMediaDocument(sticker);\n } else if (gif) {\n media = buildInputMediaDocument(gif);\n } else if (poll) {\n media = buildInputPoll(poll, randomId);\n } else if (contact) {\n media = new GramJs.InputMediaContact({\n phoneNumber: contact.phoneNumber,\n firstName: contact.firstName,\n lastName: contact.lastName,\n vcard: '',\n });\n }\n\n await prevQueue;\n\n const RequestClass = media ? GramJs.messages.SendMedia : GramJs.messages.SendMessage;\n\n await invokeRequest(new RequestClass({\n clearDraft: true,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n peer: buildInputPeer(chat.id, chat.accessHash),\n randomId,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n ...(replyingTo && { replyToMsgId: replyingTo }),\n ...(media && { media }),\n ...(noWebPage && { noWebpage: noWebPage }),\n ...(sendAs && { sendAs: buildInputPeer(sendAs.id, sendAs.accessHash) }),\n }), true);\n })();\n\n return queue;\n}\n\nconst groupedUploads: Record;\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 chat, type, query, topMessageId, minDate, maxDate, ...pagination\n}: {\n chat: ApiChat;\n type?: ApiMessageSearchType | ApiGlobalMessageSearchType;\n query?: string;\n topMessageId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterRoundVoice();\n break;\n case 'profilePhoto':\n filter = new GramJs.InputMessagesFilterChatPhotos();\n break;\n case 'text':\n default: {\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.Search({\n peer: buildInputPeer(chat.id, chat.accessHash),\n filter,\n q: query || '',\n topMsgId: topMessageId,\n minDate,\n maxDate,\n ...pagination,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(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 nextOffsetId: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextOffsetId = messages[messages.length - 1].id;\n }\n }\n\n return {\n chats,\n users,\n messages,\n totalCount,\n nextOffsetId,\n };\n}\n\nexport async function searchMessagesGlobal({\n query, offsetRate = 0, limit, type = 'text', minDate, maxDate,\n}: {\n query: string;\n offsetRate?: number;\n limit: number;\n type?: ApiGlobalMessageSearchType;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterRoundVoice();\n break;\n case 'text':\n default: {\n if (!query && !(maxDate && minDate)) {\n return undefined;\n }\n\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.SearchGlobal({\n q: query,\n offsetRate,\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n filter,\n folderId: ALL_FOLDER_ID,\n minDate,\n maxDate,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb({\n chats: result.chats,\n users: result.users,\n messages: result.messages,\n } as GramJs.messages.Messages);\n\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(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 addEntitiesWithPhotosToLocalDb(result.users);\n addEntitiesWithPhotosToLocalDb(result.chats);\n\n result.messages.forEach((message) => {\n if ((message instanceof GramJs.Message && isMessageWithMedia(message))\n || (message instanceof GramJs.MessageService && isServiceMessageWithMedia(message))\n ) {\n addMessageToLocalDb(message);\n }\n });\n}\n\nexport async function fetchPinnedMessages({ chat }: { chat: ApiChat }) {\n const result = await invokeRequest(new GramJs.messages.Search(\n {\n peer: buildInputPeer(chat.id, chat.accessHash),\n filter: new GramJs.InputMessagesFilterPinned(),\n q: '',\n limit: PINNED_MESSAGES_LIMIT,\n },\n ));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(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 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 { addEntitiesWithPhotosToLocalDb, addPhotoToLocalDb, addUserToLocalDb } 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) => Boolean(user) && !user.isSelf) as ApiUser[];\n const ids = users.map(({ id }) => id);\n\n return {\n ids,\n users,\n };\n}\n\nexport async function fetchContactList() {\n const result = await invokeRequest(new GramJs.contacts.GetContacts({ hash: BigInt('0') }));\n if (!result || result instanceof GramJs.contacts.ContactsNotModified) {\n return undefined;\n }\n\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n addUserToLocalDb(user, true);\n }\n });\n\n 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 addUserToLocalDb(user, true);\n }\n });\n\n return buildApiUsersAndStatuses(result);\n}\n\nexport async function importContact({\n phone,\n firstName,\n lastName,\n}: {\n phone?: string;\n firstName?: string;\n lastName?: string;\n}) {\n const result = await invokeRequest(new GramJs.contacts.ImportContacts({\n contacts: [buildInputContact({\n phone: phone || '',\n firstName: firstName || '',\n lastName: lastName || '',\n })],\n }));\n\n if (result instanceof GramJs.contacts.ImportedContacts && result.users.length) {\n addUserToLocalDb(result.users[0]);\n }\n\n return result?.imported.length ? buildApiPeerId(result.imported[0].userId, 'user') : undefined;\n}\n\nexport function updateContact({\n id,\n accessHash,\n phoneNumber = '',\n firstName = '',\n lastName = '',\n shouldSharePhoneNumber = false,\n}: {\n id: string;\n accessHash?: string;\n phoneNumber?: string;\n firstName?: string;\n lastName?: string;\n shouldSharePhoneNumber?: boolean;\n}) {\n return invokeRequest(new GramJs.contacts.AddContact({\n id: buildInputEntity(id, accessHash) as GramJs.InputUser,\n firstName,\n lastName,\n phone: phoneNumber,\n ...(shouldSharePhoneNumber && { addPhonePrivacyException: shouldSharePhoneNumber }),\n }), true);\n}\n\nexport async function deleteContact({\n id,\n accessHash,\n}: {\n id: string;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const result = await invokeRequest(new GramJs.contacts.DeleteContacts({ id: [input] }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteContact',\n id,\n });\n}\n\nexport async function fetchProfilePhotos(user?: ApiUser, chat?: ApiChat) {\n if (user) {\n const { id, accessHash } = user;\n\n const result = await invokeRequest(new GramJs.photos.GetUserPhotos({\n userId: buildInputEntity(id, accessHash) as GramJs.InputUser,\n limit: PROFILE_PHOTOS_LIMIT,\n offset: 0,\n maxId: BigInt('0'),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n photos: result.photos\n .filter((photo): photo is GramJs.Photo => photo instanceof GramJs.Photo)\n .map(buildApiPhoto),\n };\n }\n\n const result = await searchMessagesLocal({\n chat: chat!,\n type: 'profilePhoto',\n limit: PROFILE_PHOTOS_LIMIT,\n });\n\n if (!result) {\n return undefined;\n }\n\n const { messages, users } = result;\n\n return {\n photos: messages.map((message) => message.content.action!.photo).filter(Boolean as any),\n users,\n };\n}\n\nexport function reportSpam(userOrChat: ApiUser | ApiChat) {\n const { id, accessHash } = userOrChat;\n\n return invokeRequest(new GramJs.messages.ReportSpam({\n peer: buildInputPeer(id, accessHash),\n }), true);\n}\n\nfunction updateLocalDb(result: (GramJs.photos.Photos | GramJs.photos.PhotosSlice | GramJs.messages.Chats)) {\n if ('chats' in result) {\n addEntitiesWithPhotosToLocalDb(result.chats);\n }\n\n if ('photos' in result) {\n result.photos.forEach(addPhotoToLocalDb);\n }\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { 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 fetchAnimatedEmojiEffects() {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: new GramJs.InputStickerSetAnimatedEmojiAnimations(),\n }));\n\n if (!(result instanceof GramJs.messages.StickerSet)) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n };\n}\n\nexport async function searchStickers({ query, hash = '0' }: { query: string; hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.SearchStickerSets({\n q: query,\n hash: BigInt(hash),\n }));\n\n if (!result || result instanceof GramJs.messages.FoundStickerSetsNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function fetchSavedGifs({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetSavedGifs({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.SavedGifsNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n gifs: processGifResult(result.gifs),\n };\n}\n\nexport function saveGif({ gif, shouldUnsave }: { gif: ApiVideo; shouldUnsave?: boolean }) {\n const request = new GramJs.messages.SaveGif({\n id: buildInputDocument(gif),\n unsave: shouldUnsave,\n });\n\n return invokeRequest(request, true);\n}\n\nexport async function installStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.InstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: Date.now() },\n });\n }\n}\n\nexport async function uninstallStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.UninstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: undefined },\n });\n }\n}\n\nlet inputGifBot: GramJs.InputUser | undefined;\n\nexport async function searchGifs({ query, offset = '' }: { query: string; offset?: string }) {\n if (!inputGifBot) {\n const config = await invokeRequest(new GramJs.help.GetConfig());\n if (!config) {\n return undefined;\n }\n\n const resolvedPeer = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username: config.gifSearchUsername,\n }));\n if (!resolvedPeer || !(resolvedPeer.users[0] instanceof GramJs.User)) {\n return undefined;\n }\n\n inputGifBot = new GramJs.InputUser({\n userId: (resolvedPeer.peer as GramJs.PeerUser).userId,\n accessHash: resolvedPeer.users[0].accessHash!,\n });\n }\n\n const result = await invokeRequest(new GramJs.messages.GetInlineBotResults({\n bot: inputGifBot,\n peer: new GramJs.InputPeerEmpty(),\n query,\n offset,\n }));\n if (!result) {\n return undefined;\n }\n\n const documents = result.results\n .map((foundGif) => {\n if (foundGif instanceof GramJs.BotInlineMediaResult) {\n return foundGif.document;\n }\n\n return undefined;\n })\n .filter(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, ApiUser, OnApiUpdate } from '../../types';\nimport { addEntitiesWithPhotosToLocalDb } from '../helpers';\nimport { buildApiExportedInvite, buildChatInviteImporter } from '../apiBuilders/chats';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport function checkChatUsername({ username }: { username: string }) {\n return invokeRequest(new GramJs.channels.CheckUsername({\n channel: new GramJs.InputChannelEmpty(),\n username,\n }));\n}\n\nexport async function setChatUsername(\n { chat, username }: { chat: ApiChat; username: string },\n) {\n const result = await invokeRequest(new GramJs.channels.UpdateUsername({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n username,\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { username },\n });\n }\n}\n\nexport async function updatePrivateLink({\n chat, usageLimit, expireDate,\n}: {\n chat: ApiChat; usageLimit?: number; expireDate?: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.ExportChatInvite({\n peer: buildInputPeer(chat.id, chat.accessHash),\n usageLimit,\n expireDate,\n }));\n\n 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\nexport async function fetchExportedChatInvites({\n peer, admin, limit = 0, isRevoked,\n}: { peer: ApiChat; admin: ApiUser; limit: number; isRevoked?: boolean }) {\n const exportedInvites = await invokeRequest(new GramJs.messages.GetExportedChatInvites({\n peer: buildInputPeer(peer.id, peer.accessHash),\n adminId: buildInputEntity(admin.id, admin.accessHash) as GramJs.InputUser,\n limit,\n revoked: isRevoked || undefined,\n }));\n\n if (!exportedInvites) return undefined;\n addEntitiesWithPhotosToLocalDb(exportedInvites.users);\n return exportedInvites.invites.map(buildApiExportedInvite);\n}\n\nexport async function editExportedChatInvite({\n peer, isRevoked, link, expireDate, usageLimit, isRequestNeeded, title,\n}: {\n peer: ApiChat;\n isRevoked?: boolean;\n link: string;\n expireDate?: number;\n usageLimit?: number;\n isRequestNeeded?: boolean;\n title?: string;\n}) {\n const invite = await invokeRequest(new GramJs.messages.EditExportedChatInvite({\n link,\n peer: buildInputPeer(peer.id, peer.accessHash),\n expireDate,\n usageLimit: !isRequestNeeded ? usageLimit : undefined,\n requestNeeded: isRequestNeeded,\n title,\n revoked: isRevoked || undefined,\n }));\n\n if (!invite) return undefined;\n\n addEntitiesWithPhotosToLocalDb(invite.users);\n if (invite instanceof GramJs.messages.ExportedChatInvite) {\n const replaceInvite = buildApiExportedInvite(invite.invite);\n return {\n oldInvite: replaceInvite,\n newInvite: replaceInvite,\n };\n }\n\n if (invite instanceof GramJs.messages.ExportedChatInviteReplaced) {\n const oldInvite = buildApiExportedInvite(invite.invite);\n const newInvite = buildApiExportedInvite(invite.newInvite);\n return {\n oldInvite,\n newInvite,\n };\n }\n return undefined;\n}\n\nexport async function exportChatInvite({\n peer, expireDate, usageLimit, isRequestNeeded, title,\n}: {\n peer: ApiChat;\n expireDate?: number;\n usageLimit?: number;\n isRequestNeeded?: boolean;\n title?: string;\n}) {\n const invite = await invokeRequest(new GramJs.messages.ExportChatInvite({\n peer: buildInputPeer(peer.id, peer.accessHash),\n expireDate,\n usageLimit: !isRequestNeeded ? usageLimit : undefined,\n requestNeeded: isRequestNeeded || undefined,\n title,\n }));\n\n if (!invite) return undefined;\n return buildApiExportedInvite(invite);\n}\n\nexport async function deleteExportedChatInvite({\n peer, link,\n}: {\n peer: ApiChat; link: string;\n}) {\n const result = await invokeRequest(new GramJs.messages.DeleteExportedChatInvite({\n peer: buildInputPeer(peer.id, peer.accessHash),\n link,\n }));\n\n return result;\n}\n\nexport async function deleteRevokedExportedChatInvites({\n peer, admin,\n}: {\n peer: ApiChat; admin: ApiUser;\n}) {\n const result = await invokeRequest(new GramJs.messages.DeleteRevokedExportedChatInvites({\n peer: buildInputPeer(peer.id, peer.accessHash),\n adminId: buildInputEntity(admin.id, admin.accessHash) as GramJs.InputUser,\n }));\n\n return result;\n}\n\nexport async function fetchChatInviteImporters({\n peer, link, offsetDate = 0, offsetUser, limit = 0, isRequested,\n}: {\n peer: ApiChat; link?: string; offsetDate: number; offsetUser?: ApiUser; limit: number; isRequested?: boolean;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetChatInviteImporters({\n peer: buildInputPeer(peer.id, peer.accessHash),\n link,\n offsetDate,\n offsetUser: offsetUser\n ? buildInputEntity(offsetUser.id, offsetUser.accessHash) as GramJs.InputUser : new GramJs.InputUserEmpty(),\n limit,\n requested: isRequested || undefined,\n }));\n\n if (!result) return undefined;\n addEntitiesWithPhotosToLocalDb(result.users);\n return result.importers.map((importer) => buildChatInviteImporter(importer));\n}\n\nexport function hideChatJoinRequest({\n peer,\n user,\n isApproved,\n}: {\n peer: ApiChat;\n user: ApiUser;\n isApproved: boolean;\n}) {\n return invokeRequest(new GramJs.messages.HideChatJoinRequest({\n peer: buildInputPeer(peer.id, peer.accessHash),\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n approved: isApproved || undefined,\n }), true);\n}\n\nexport function hideAllChatJoinRequests({\n peer,\n isApproved,\n link,\n}: {\n peer: ApiChat;\n isApproved: boolean;\n link?: string;\n}) {\n return invokeRequest(new GramJs.messages.HideAllChatJoinRequests({\n peer: buildInputPeer(peer.id, peer.accessHash),\n approved: isApproved || undefined,\n link,\n }), true);\n}\n\nexport function hideChatReportPanel(chat: ApiChat) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.messages.HidePeerSettingsBar({\n peer: buildInputPeer(id, accessHash),\n }));\n}\n","import { Api as GramJs, errors } from '../../../lib/gramjs';\n\nimport { 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: any) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function clearPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ currentPassword });\n\n return true;\n } catch (err: any) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updatePassword(currentPassword: string, password: string, hint?: string, email?: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: password,\n hint,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err: any) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updateRecoveryEmail(currentPassword: string, email: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: currentPassword,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err: any) {\n onError(err);\n\n return false;\n }\n}\n\nexport function provideRecoveryEmailCode(code: string) {\n emailCodeController.resolve!(code);\n}\n\nfunction onError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateTwoFaError',\n message,\n });\n}\n","import { 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 }));\n\n if (!result) return undefined;\n\n if (result instanceof GramJs.Updates) {\n const update = result.updates.find((u) => u instanceof GramJs.UpdateGroupCall);\n if (!(update instanceof GramJs.UpdateGroupCall)) return undefined;\n\n return buildApiGroupCall(update.call);\n }\n\n return undefined;\n}\n\nexport async function createGroupCall({\n peer,\n}: {\n peer: ApiChat;\n}) {\n const randomId = generateRandomInt();\n const result = await invokeRequest(new GramJs.phone.CreateGroupCall({\n peer: buildInputPeer(peer.id, peer.accessHash),\n randomId,\n }));\n\n if (!result) return undefined;\n\n if (result instanceof GramJs.Updates) {\n const update = result.updates[0];\n if (update instanceof GramJs.UpdateGroupCall) {\n return buildApiGroupCall(update.call);\n }\n }\n\n return undefined;\n}\n\nexport function joinGroupCallPresentation({\n call, params,\n}: {\n call: ApiGroupCall; params: JoinGroupCallPayload;\n}) {\n return invokeRequest(new GramJs.phone.JoinGroupCallPresentation({\n call: buildInputGroupCall(call),\n params: new GramJs.DataJSON({\n data: JSON.stringify(params),\n }),\n }), true);\n}\n\nexport function toggleGroupCallStartSubscription({\n call, subscribed,\n}: {\n call: ApiGroupCall; subscribed: boolean;\n}) {\n return invokeRequest(new GramJs.phone.ToggleGroupCallStartSubscription({\n call: buildInputGroupCall(call),\n subscribed,\n }), true);\n}\n\nexport function leaveGroupCallPresentation({\n call,\n}: {\n call: ApiGroupCall;\n}) {\n return invokeRequest(new GramJs.phone.LeaveGroupCallPresentation({\n call: buildInputGroupCall(call),\n }), true);\n}\n","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, OnApiUpdate } from '../../types';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\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 async 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 const result = await 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 }));\n\n if (result instanceof GramJs.payments.PaymentVerificationNeeded) {\n onUpdate({\n '@type': 'updatePaymentVerificationNeeded',\n url: result.url,\n });\n\n return undefined;\n }\n\n return Boolean(result);\n}\n\nexport async function getPaymentForm({\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 { 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 publicToken: nativeData?.public_token,\n },\n };\n}\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport BigInt from 'big-integer';\nimport localDb from '../localDb';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiAppConfig } from '../../types';\nimport { buildJson } from './misc';\n\ntype GramJsAppConfig = {\n emojies_sounds: Record;\n emojies_send_dice: string[];\n groupcall_video_participants_max: number;\n reactions_default: string;\n reactions_uniq_max: number;\n chat_read_mark_size_threshold: number;\n chat_read_mark_expire_period: number;\n};\n\nfunction buildEmojiSounds(appConfig: GramJsAppConfig) {\n const { emojies_sounds } = appConfig;\n return Object.keys(emojies_sounds).reduce((acc: Record, key) => {\n const l = emojies_sounds[key];\n localDb.documents[l.id] = new GramJs.Document({\n id: BigInt(l.id),\n accessHash: BigInt(l.access_hash),\n dcId: 1,\n mimeType: 'audio/ogg',\n fileReference: Buffer.from(atob(l.file_reference_base64\n .replace(/-/g, '+')\n .replace(/_/g, '/'))),\n } as GramJs.Document);\n\n acc[key] = l.id;\n return acc;\n }, {});\n}\n\nexport function buildApiConfig(json: GramJs.TypeJSONValue): ApiAppConfig {\n const appConfig = buildJson(json) as GramJsAppConfig;\n\n return {\n emojiSounds: buildEmojiSounds(appConfig),\n defaultReaction: appConfig.reactions_default,\n seenByMaxChatMembers: appConfig.chat_read_mark_size_threshold,\n seenByExpiresAt: appConfig.chat_read_mark_expire_period,\n };\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport {\n ApiAppConfig,\n ApiChat,\n ApiLangString,\n ApiLanguage,\n ApiNotifyException,\n ApiUser,\n ApiWallpaper,\n} from '../../types';\nimport { ApiPrivacyKey, InputPrivacyRules, LangCode } from '../../../types';\n\nimport { BLOCKED_LIST_LIMIT, DEFAULT_LANG_PACK, LANG_PACKS } from '../../../config';\nimport {\n buildApiCountryList,\n buildApiNotifyException,\n buildApiSession,\n buildApiWallpaper,\n buildPrivacyRules,\n} from '../apiBuilders/misc';\n\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildInputEntity, buildInputPeer, buildInputPrivacyKey } from '../gramjsBuilders';\nimport { getClient, invokeRequest, uploadFile } from './client';\nimport { omitVirtualClassFields } from '../apiBuilders/helpers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { getServerTime } from '../../../util/serverTime';\nimport { getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\nimport localDb from '../localDb';\nimport { buildApiConfig } from '../apiBuilders/appConfig';\nimport { addEntitiesWithPhotosToLocalDb } from '../helpers';\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 }), true);\n}\n\nexport function checkUsername(username: string) {\n return invokeRequest(new GramJs.account.CheckUsername({ username }));\n}\n\nexport function updateUsername(username: string) {\n return invokeRequest(new GramJs.account.UpdateUsername({ username }), true);\n}\n\nexport async function updateProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n return invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }), true);\n}\n\nexport async function uploadProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n await invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function fetchWallpapers() {\n const result = await invokeRequest(new GramJs.account.GetWallPapers({ hash: BigInt('0') }));\n\n if (!result || result instanceof GramJs.account.WallPapersNotModified) {\n return undefined;\n }\n\n const filteredWallpapers = result.wallpapers.filter((wallpaper) => {\n if (\n !(wallpaper instanceof GramJs.WallPaper)\n || !(wallpaper.document instanceof GramJs.Document)\n ) {\n return false;\n }\n\n return !wallpaper.pattern && wallpaper.document.mimeType !== 'application/x-tgwallpattern';\n }) as GramJs.WallPaper[];\n\n filteredWallpapers.forEach((wallpaper) => {\n localDb.documents[String(wallpaper.document.id)] = wallpaper.document as GramJs.Document;\n });\n\n return {\n wallpapers: filteredWallpapers.map(buildApiWallpaper).filter(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({\n compareSound: true,\n }), undefined, undefined, true);\n\n if (!(result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined)) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return result.updates.reduce((acc, update) => {\n if (!(update instanceof GramJs.UpdateNotifySettings && update.peer instanceof GramJs.NotifyPeer)) {\n return acc;\n }\n\n acc.push(buildApiNotifyException(update.notifySettings, update.peer.peer, serverTimeOffset));\n\n return acc;\n }, [] as ApiNotifyException[]);\n}\n\nexport async function fetchNotificationSettings({\n serverTimeOffset,\n}: { serverTimeOffset: number }) {\n const [\n isMutedContactSignUpNotification,\n privateContactNotificationsSettings,\n groupNotificationsSettings,\n broadcastNotificationsSettings,\n ] = await Promise.all([\n invokeRequest(new GramJs.account.GetContactSignUpNotification()),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyUsers(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyChats(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyBroadcasts(),\n })),\n ]);\n\n if (!privateContactNotificationsSettings || !groupNotificationsSettings || !broadcastNotificationsSettings) {\n return false;\n }\n\n const {\n silent: privateSilent, muteUntil: privateMuteUntil, showPreviews: privateShowPreviews,\n } = privateContactNotificationsSettings;\n const {\n silent: groupSilent, muteUntil: groupMuteUntil, showPreviews: groupShowPreviews,\n } = groupNotificationsSettings;\n const {\n silent: broadcastSilent, muteUntil: broadcastMuteUntil, showPreviews: broadcastShowPreviews,\n } = broadcastNotificationsSettings;\n\n return {\n hasContactJoinedNotifications: !isMutedContactSignUpNotification,\n hasPrivateChatsNotifications: !(\n privateSilent\n || (typeof privateMuteUntil === 'number' && getServerTime(serverTimeOffset) < privateMuteUntil)\n ),\n hasPrivateChatsMessagePreview: privateShowPreviews,\n hasGroupNotifications: !(\n groupSilent || (typeof groupMuteUntil === 'number'\n && getServerTime(serverTimeOffset) < groupMuteUntil)\n ),\n hasGroupMessagePreview: groupShowPreviews,\n hasBroadcastNotifications: !(\n broadcastSilent || (typeof broadcastMuteUntil === 'number'\n && getServerTime(serverTimeOffset) < broadcastMuteUntil)\n ),\n hasBroadcastMessagePreview: broadcastShowPreviews,\n };\n}\n\nexport function updateContactSignUpNotification(isSilent: boolean) {\n return invokeRequest(new GramJs.account.SetContactSignUpNotification({ silent: isSilent }));\n}\n\nexport function updateNotificationSettings(peerType: 'contact' | 'group' | 'broadcast', {\n isSilent,\n shouldShowPreviews,\n}: {\n isSilent: boolean;\n shouldShowPreviews: boolean;\n}) {\n let peer: GramJs.TypeInputNotifyPeer;\n if (peerType === 'contact') {\n peer = new GramJs.InputNotifyUsers();\n } else if (peerType === 'group') {\n peer = new GramJs.InputNotifyChats();\n } else {\n peer = new GramJs.InputNotifyBroadcasts();\n }\n\n const settings = {\n showPreviews: shouldShowPreviews,\n silent: isSilent,\n muteUntil: isSilent ? MAX_INT_32 : 0,\n };\n\n return invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer,\n settings: new GramJs.InputPeerNotifySettings(settings),\n }));\n}\n\nexport async function fetchLanguages(): Promise {\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()) as typeof collections[0] };\n}\n\nexport async function fetchLangStrings({ langPack, langCode, keys }: {\n langPack: string; langCode: string; keys: string[];\n}) {\n const result = await invokeRequest(new GramJs.langpack.GetStrings({\n langPack,\n langCode: BETA_LANG_CODES.includes(langCode) ? `${langCode}-raw` : langCode,\n keys,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return result.map(omitVirtualClassFields);\n}\n\nexport async function fetchPrivacySettings(privacyKey: ApiPrivacyKey) {\n const key = buildInputPrivacyKey(privacyKey);\n const result = await invokeRequest(new GramJs.account.GetPrivacy({ key }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nexport function registerDevice(token: string) {\n const client = getClient();\n const secret = client.session.getAuthKey().getKey();\n return invokeRequest(new GramJs.account.RegisterDevice({\n tokenType: 10,\n secret,\n appSandbox: false,\n otherUids: [],\n token,\n }));\n}\n\nexport function unregisterDevice(token: string) {\n return invokeRequest(new GramJs.account.UnregisterDevice({\n tokenType: 10,\n otherUids: [],\n token,\n }));\n}\n\nexport async function setPrivacySettings(\n privacyKey: ApiPrivacyKey, rules: InputPrivacyRules,\n) {\n const key = buildInputPrivacyKey(privacyKey);\n const privacyRules: GramJs.TypeInputPrivacyRule[] = [];\n\n if (rules.allowedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowUsers({\n users: rules.allowedUsers.map(({ id, accessHash }) => buildInputEntity(id, accessHash) as GramJs.InputUser),\n }));\n }\n if (rules.allowedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowChatParticipants({\n chats: rules.allowedChats.map(({ id }) => buildInputEntity(id) as BigInt.BigInteger),\n }));\n }\n if (rules.blockedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowUsers({\n users: rules.blockedUsers.map(({ id, accessHash }) => buildInputEntity(id, accessHash) as GramJs.InputUser),\n }));\n }\n if (rules.blockedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowChatParticipants({\n chats: rules.blockedChats.map(({ id }) => buildInputEntity(id) as BigInt.BigInteger),\n }));\n }\n switch (rules.visibility) {\n case 'everybody':\n privacyRules.push(new GramJs.InputPrivacyValueAllowAll());\n break;\n\n case 'contacts':\n privacyRules.push(new GramJs.InputPrivacyValueAllowContacts());\n break;\n\n case 'nonContacts':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowContacts());\n break;\n\n case 'nobody':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowAll());\n break;\n }\n\n const result = await invokeRequest(new GramJs.account.SetPrivacy({ key, rules: privacyRules }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nexport async function updateIsOnline(isOnline: boolean) {\n await invokeRequest(new GramJs.account.UpdateStatus({ offline: !isOnline }));\n}\n\nexport async function fetchContentSettings() {\n const result = await invokeRequest(new GramJs.account.GetContentSettings());\n if (!result) {\n return undefined;\n }\n\n return {\n isSensitiveEnabled: Boolean(result.sensitiveEnabled),\n canChangeSensitive: Boolean(result.sensitiveCanChange),\n };\n}\n\nexport function updateContentSettings(isEnabled: boolean) {\n return invokeRequest(new GramJs.account.SetContentSettings({\n sensitiveEnabled: isEnabled || undefined,\n }));\n}\n\nexport async function fetchAppConfig(): Promise {\n const result = await invokeRequest(new GramJs.help.GetAppConfig());\n if (!result) return undefined;\n\n return buildApiConfig(result);\n}\n\nfunction updateLocalDb(\n result: (\n GramJs.account.PrivacyRules | GramJs.contacts.Blocked | GramJs.contacts.BlockedSlice |\n GramJs.Updates | GramJs.UpdatesCombined\n ),\n) {\n addEntitiesWithPhotosToLocalDb(result.users);\n addEntitiesWithPhotosToLocalDb(result.chats);\n}\n\nexport async function fetchCountryList({ langCode = 'en' }: { langCode?: LangCode }) {\n const countryList = await invokeRequest(new GramJs.help.GetCountriesList({\n langCode,\n }));\n\n if (!(countryList instanceof GramJs.help.CountriesList)) {\n return undefined;\n }\n return buildApiCountryList(countryList.countries);\n}\n","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';\nimport { omitVirtualClassFields } from '../apiBuilders/helpers';\n\nexport function init() {\n}\n\nexport async function answerCallbackButton({\n chatId, accessHash, messageId, data,\n}: {\n chatId: string; accessHash?: string; messageId: number; data: string;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetBotCallbackAnswer({\n peer: buildInputPeer(chatId, accessHash),\n msgId: messageId,\n data: deserializeBytes(data),\n }));\n\n return result ? omitVirtualClassFields(result) : undefined;\n}\n\nexport async function fetchTopInlineBots() {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\n botsInline: true,\n }));\n\n if (!(topPeers instanceof GramJs.contacts.TopPeers)) {\n return undefined;\n }\n\n const users = topPeers.users.map(buildApiUser).filter(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, isSilent, scheduleDate,\n}: {\n chat: ApiChat;\n resultId: string;\n queryId: string;\n replyingTo?: number;\n sendAs?: ApiUser | ApiChat;\n isSilent?: boolean;\n scheduleDate?: number;\n}) {\n const randomId = generateRandomBigInt();\n\n await invokeRequest(new GramJs.messages.SendInlineBotResult({\n clearDraft: true,\n randomId,\n queryId: BigInt(queryId),\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: resultId,\n scheduleDate,\n ...(isSilent && { silent: true }),\n ...(replyingTo && { replyToMsgId: replyingTo }),\n ...(sendAs && { sendAs: buildInputPeer(sendAs.id, sendAs.accessHash) }),\n }), true);\n}\n\nexport async function startBot({\n bot, startParam,\n}: {\n bot: ApiUser;\n startParam?: string;\n}) {\n const randomId = generateRandomBigInt();\n\n await invokeRequest(new GramJs.messages.StartBot({\n bot: buildInputPeer(bot.id, bot.accessHash),\n peer: buildInputPeer(bot.id, bot.accessHash),\n randomId,\n startParam,\n }), true);\n}\n\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 { ApiChat, ApiUser } from '../../types';\nimport { invokeRequest } from './client';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { buildInputPeer } from '../gramjsBuilders';\nimport localDb from '../localDb';\nimport { buildApiAvailableReaction, buildMessagePeerReaction } from '../apiBuilders/messages';\nimport { REACTION_LIST_LIMIT } from '../../../config';\nimport { addEntitiesWithPhotosToLocalDb } from '../helpers';\nimport { buildApiUser } from '../apiBuilders/users';\n\nexport function sendWatchingEmojiInteraction({\n chat,\n emoticon,\n}: {\n chat: ApiChat; emoticon: string;\n}) {\n return invokeRequest(new GramJs.messages.SetTyping({\n peer: buildInputPeer(chat.id, chat.accessHash),\n action: new GramJs.SendMessageEmojiInteractionSeen({\n emoticon,\n }),\n }));\n}\n\nexport function sendEmojiInteraction({\n chat,\n emoticon,\n messageId,\n timestamps,\n}: {\n chat: ApiChat; messageId: number; emoticon: string; timestamps: number[];\n}) {\n return invokeRequest(new GramJs.messages.SetTyping({\n peer: buildInputPeer(chat.id, chat.accessHash),\n action: new GramJs.SendMessageEmojiInteraction({\n emoticon,\n msgId: messageId,\n interaction: new GramJs.DataJSON({\n data: JSON.stringify({\n v: 1,\n a: timestamps.map((t: number) => ({\n t,\n i: 1,\n })),\n }),\n }),\n }),\n }));\n}\n\nexport async function getAvailableReactions() {\n const result = await invokeRequest(new GramJs.messages.GetAvailableReactions({}));\n\n if (!result || result instanceof GramJs.messages.AvailableReactionsNotModified) {\n return undefined;\n }\n\n result.reactions.forEach((reaction) => {\n if (reaction.staticIcon instanceof GramJs.Document) {\n localDb.documents[String(reaction.staticIcon.id)] = reaction.staticIcon;\n }\n if (reaction.selectAnimation instanceof GramJs.Document) {\n localDb.documents[String(reaction.selectAnimation.id)] = reaction.selectAnimation;\n }\n if (reaction.aroundAnimation instanceof GramJs.Document) {\n localDb.documents[String(reaction.aroundAnimation.id)] = reaction.aroundAnimation;\n }\n if (reaction.centerIcon instanceof GramJs.Document) {\n localDb.documents[String(reaction.centerIcon.id)] = reaction.centerIcon;\n }\n });\n\n return result.reactions.map(buildApiAvailableReaction);\n}\n\nexport function sendReaction({\n chat, messageId, reaction,\n}: {\n chat: ApiChat; messageId: number; reaction?: string;\n}) {\n return invokeRequest(new GramJs.messages.SendReaction({\n ...(reaction && { reaction }),\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n }), true);\n}\n\nexport function fetchMessageReactions({\n ids, chat,\n}: {\n ids: number[]; chat: ApiChat;\n}) {\n return invokeRequest(new GramJs.messages.GetMessagesReactions({\n id: ids,\n peer: buildInputPeer(chat.id, chat.accessHash),\n }), true);\n}\n\nexport async function fetchMessageReactionsList({\n chat, messageId, reaction, offset,\n}: {\n chat: ApiChat; messageId: number; reaction?: string; offset?: string;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetMessageReactionsList({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageId,\n ...(reaction && { reaction }),\n limit: REACTION_LIST_LIMIT,\n ...(offset && { offset }),\n }));\n\n if (!result) {\n return undefined;\n }\n\n addEntitiesWithPhotosToLocalDb(result.users);\n\n const { nextOffset, reactions, count } = result;\n\n return {\n users: result.users.map(buildApiUser).filter(Boolean as any),\n nextOffset,\n reactions: reactions.map(buildMessagePeerReaction),\n count,\n };\n}\n\nexport function setDefaultReaction({\n reaction,\n}: {\n reaction: string;\n}) {\n return invokeRequest(new GramJs.messages.SetDefaultReaction({\n reaction,\n }));\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChannelStatistics,\n ApiGroupStatistics,\n StatisticsGraph,\n StatisticsOverviewItem,\n StatisticsOverviewPercentage,\n StatisticsOverviewPeriod,\n} from '../../types';\n\nexport function buildChannelStatistics(stats: GramJs.stats.BroadcastStats): ApiChannelStatistics {\n return {\n // Graphs\n growthGraph: buildGraph(stats.growthGraph),\n followersGraph: buildGraph(stats.followersGraph),\n muteGraph: buildGraph(stats.muteGraph),\n topHoursGraph: buildGraph(stats.topHoursGraph),\n\n // Async graphs\n languagesGraph: (stats.languagesGraph as GramJs.StatsGraphAsync).token,\n viewsBySourceGraph: (stats.viewsBySourceGraph as GramJs.StatsGraphAsync).token,\n newFollowersBySourceGraph: (stats.newFollowersBySourceGraph as GramJs.StatsGraphAsync).token,\n interactionsGraph: (stats.interactionsGraph as GramJs.StatsGraphAsync).token,\n\n // Statistics overview\n followers: buildStatisticsOverview(stats.followers),\n viewsPerPost: buildStatisticsOverview(stats.viewsPerPost),\n sharesPerPost: buildStatisticsOverview(stats.sharesPerPost),\n enabledNotifications: buildStatisticsPercentage(stats.enabledNotifications),\n\n // Recent posts\n recentTopMessages: stats.recentMessageInteractions,\n };\n}\n\nexport function buildGroupStatistics(stats: GramJs.stats.MegagroupStats): ApiGroupStatistics {\n return {\n // Graphs\n growthGraph: buildGraph(stats.growthGraph),\n membersGraph: buildGraph(stats.membersGraph),\n topHoursGraph: buildGraph(stats.topHoursGraph),\n\n // Async graphs\n languagesGraph: (stats.languagesGraph as GramJs.StatsGraphAsync).token,\n messagesGraph: (stats.messagesGraph as GramJs.StatsGraphAsync).token,\n actionsGraph: (stats.actionsGraph as GramJs.StatsGraphAsync).token,\n\n // Statistics overview\n period: getOverviewPeriod(stats.period),\n members: buildStatisticsOverview(stats.members),\n viewers: buildStatisticsOverview(stats.viewers),\n messages: buildStatisticsOverview(stats.messages),\n posters: buildStatisticsOverview(stats.posters),\n };\n}\n\nexport function buildGraph(result: GramJs.TypeStatsGraph, isPercentage?: boolean): StatisticsGraph {\n if ((result as GramJs.StatsGraphError).error) {\n throw new Error((result as GramJs.StatsGraphError).error);\n }\n\n const data = JSON.parse((result as GramJs.StatsGraph).json.data);\n const [x, ...y] = data.columns;\n const hasSecondYAxis = data.y_scaled;\n\n return {\n type: isPercentage ? 'area' : data.types.y0,\n zoomToken: (result as GramJs.StatsGraph).zoomToken,\n labelFormatter: data.xTickFormatter,\n tooltipFormatter: data.xTooltipFormatter,\n labels: x.slice(1),\n hideCaption: !data.subchart.show,\n hasSecondYAxis,\n isStacked: data.stacked && !hasSecondYAxis,\n isPercentage,\n datasets: y.map((item: any) => {\n const key = item[0];\n\n return {\n name: data.names[key],\n color: extractColor(data.colors[key]),\n values: item.slice(1),\n };\n }),\n ...calculateMinimapRange(data.subchart.defaultZoom, x.slice(1)),\n };\n}\n\nfunction extractColor(color: string): string {\n return color.substring(color.indexOf('#'));\n}\n\nfunction calculateMinimapRange(range: Array, values: Array) {\n const [min, max] = range;\n\n let minIndex = 0;\n let maxIndex = values.length - 1;\n\n values.forEach((item, index) => {\n if (!minIndex && item >= min) {\n minIndex = index;\n }\n\n if (!maxIndex && item >= max) {\n maxIndex = index;\n }\n });\n\n const begin = Math.max(0, minIndex / (values.length - 1));\n const end = Math.min(1, maxIndex / (values.length - 1));\n\n return { minimapRange: { begin, end }, labelFromIndex: minIndex, labelToIndex: maxIndex };\n}\n\nfunction buildStatisticsOverview({ current, previous }: GramJs.StatsAbsValueAndPrev): StatisticsOverviewItem {\n const change = current - previous;\n\n return {\n current,\n change,\n ...(previous && { percentage: (change ? ((Math.abs(change) / previous) * 100) : 0).toFixed(2) }),\n };\n}\n\nfunction buildStatisticsPercentage(data: GramJs.StatsPercentValue): StatisticsOverviewPercentage {\n return {\n percentage: ((data.part / data.total) * 100).toFixed(2),\n };\n}\n\nfunction getOverviewPeriod(data: GramJs.StatsDateRangeDays): StatisticsOverviewPeriod {\n return {\n maxDate: data.maxDate,\n minDate: data.minDate,\n };\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport {\n ApiChat, ApiChannelStatistics, ApiGroupStatistics, StatisticsGraph,\n} from '../../types';\n\nimport { invokeRequest } from './client';\nimport { buildInputEntity } from '../gramjsBuilders';\nimport { buildChannelStatistics, buildGroupStatistics, buildGraph } from '../apiBuilders/statistics';\n\nexport async function fetchChannelStatistics({\n chat,\n}: { chat: ApiChat }): Promise {\n const result = await invokeRequest(new GramJs.stats.GetBroadcastStats({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n }), undefined, undefined, undefined, chat.fullInfo!.statisticsDcId);\n\n if (!result) {\n return undefined;\n }\n\n return buildChannelStatistics(result);\n}\n\nexport async function fetchGroupStatistics({\n chat,\n}: { chat: ApiChat }): Promise {\n const result = await invokeRequest(new GramJs.stats.GetMegagroupStats({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n }), undefined, undefined, undefined, chat.fullInfo!.statisticsDcId);\n\n if (!result) {\n return undefined;\n }\n\n return buildGroupStatistics(result);\n}\n\nexport async function fetchStatisticsAsyncGraph({\n token,\n x,\n isPercentage,\n dcId,\n}: {\n token: string;\n x?: number;\n isPercentage?: boolean;\n dcId?: number;\n}): Promise {\n const result = await invokeRequest(new GramJs.stats.LoadAsyncGraph({\n token,\n ...(x && { x: BigInt(x) }),\n }), undefined, undefined, undefined, dcId);\n\n if (!result) {\n return undefined;\n }\n\n return buildGraph(result as GramJs.StatsGraph, isPercentage);\n}\n","import {\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 { init as initPayments } from './methods/payments';\nimport * as methods from './methods';\n\nlet onUpdate: OnApiUpdate;\n\nexport async function initApi(_onUpdate: OnApiUpdate, initialArgs: ApiInitialArgs) {\n onUpdate = _onUpdate;\n\n initUpdater(handleUpdate);\n initAuth(handleUpdate);\n initChats(handleUpdate);\n initMessages(handleUpdate);\n initUsers(handleUpdate);\n initStickers(handleUpdate);\n initManagement(handleUpdate);\n initTwoFaSettings(handleUpdate);\n initCalls(handleUpdate);\n initPayments(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\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\n if (DEBUG && typeof response === 'object' && 'CONSTRUCTOR_ID' in response) {\n // eslint-disable-next-line no-console\n console.error(`[GramJs/worker] \\`${name}\\`: Unexpected response \\`${(response as any).className}\\``);\n }\n\n const { arrayBuffer } = (typeof response === 'object' && 'arrayBuffer' in response && response) || {};\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n response,\n }, arrayBuffer);\n }\n } catch (error: any) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n cancelApiProgress(callback);\n }\n\n break;\n }\n case 'ping': {\n sendToOrigin({\n type: 'methodResponse',\n messageId: data.messageId!,\n });\n\n break;\n }\n }\n};\n\nfunction handleErrors() {\n self.onerror = (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.error.message || 'Uncaught exception in worker' } });\n };\n\n self.addEventListener('unhandledrejection', (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.reason.message || 'Uncaught rejection in worker' } });\n });\n}\n\nfunction onUpdate(update: ApiUpdate) {\n sendToOrigin({\n type: 'update',\n update,\n });\n}\n\nfunction sendToOrigin(data: WorkerMessageData, arrayBuffer?: ArrayBuffer) {\n if (arrayBuffer) {\n postMessage(data, [arrayBuffer]);\n } else {\n postMessage(data);\n }\n}\n","const BigInt = require('big-integer');\nconst crypto = require('./crypto/crypto');\n\n/**\n * converts a buffer to big int\n * @param buffer\n * @param little\n * @param signed\n * @returns {bigInt.BigInteger}\n */\nfunction readBigIntFromBuffer(buffer, little = true, signed = false) {\n let randBuffer = Buffer.from(buffer);\n const bytesNumber = randBuffer.length;\n if (little) {\n randBuffer = randBuffer.reverse();\n }\n let bigInt = BigInt(randBuffer.toString('hex'), 16);\n if (signed && Math.floor(bigInt.toString('2').length / 8) >= bytesNumber) {\n bigInt = bigInt.subtract(BigInt(2)\n .pow(BigInt(bytesNumber * 8)));\n }\n return bigInt;\n}\n\n/**\n * Special case signed little ints\n * @param big\n * @param number\n * @returns {Buffer}\n */\nfunction toSignedLittleBuffer(big, number = 8) {\n const bigNumber = BigInt(big);\n const byteArray = [];\n for (let i = 0; i < number; i++) {\n byteArray[i] = bigNumber.shiftRight(8 * i)\n .and(255);\n }\n return Buffer.from(byteArray);\n}\n\n\n/**\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, 0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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 (Boolean(item) &&\n typeof item === 'object' &&\n typeof (item.length) === 'number' &&\n (item.length === 0 ||\n (item.length > 0 &&\n (item.length - 1) in item)\n )\n )\n )\n}\n*/\n/**\n * Returns the appropriate DC based on the id\n * @param dcId the id of the DC.\n * @param downloadDC whether to use -1 DCs or not\n * (These only support downloading/uploading and not creating a new AUTH key)\n * @return {{port: number, ipAddress: string, id: number}}\n */\nfunction getDC(dcId, downloadDC = false) {\n // TODO Move to external config\n switch (dcId) {\n case 1:\n return {\n id: 1,\n ipAddress: `zws1${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 2:\n return {\n id: 2,\n ipAddress: `zws2${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 3:\n return {\n id: 3,\n ipAddress: `zws3${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 4:\n return {\n id: 4,\n ipAddress: `zws4${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 5:\n return {\n id: 5,\n ipAddress: `zws5${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n default:\n throw new Error(`Cannot find the DC with the ID of ${dcId}`);\n }\n // TODO chose based on current connection method\n /*\n if (!this._config) {\n this._config = await this.invoke(new requests.help.GetConfig())\n }\n if (cdn && !this._cdnConfig) {\n this._cdnConfig = await this.invoke(new requests.help.GetCdnConfig())\n for (const pk of this._cdnConfig.publicKeys) {\n addKey(pk.publicKey)\n }\n }\n for (const DC of this._config.dcOptions) {\n if (DC.id === dcId && Boolean(DC.ipv6) === this._useIPV6 && Boolean(DC.cdn) === cdn) {\n return DC\n }\n } */\n}\n\nmodule.exports = {\n getMessageId,\n // _getEntityPair,\n // getInputMessage,\n // getInputDialog,\n // getInputUser,\n // getInputChannel,\n getInputPeer,\n // parsePhone,\n // parseUsername,\n // getPeer,\n // getPeerId,\n getDisplayName,\n // resolveId,\n // isListLike,\n 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: any) {\n onEmailCodeError!(err);\n }\n }\n } else {\n throw e;\n }\n }\n}\n","const os = require('os');\nconst Logger = require('../extensions/Logger');\nconst { sleep } = require('../Helpers');\nconst errors = require('../errors');\nconst MemorySession = require('../sessions/Memory');\nconst Helpers = require('../Helpers');\nconst utils = require('../Utils');\nconst Session = require('../sessions/Abstract');\nconst { LAYER } = require('../tl/AllTLObjects');\nconst {\n constructors,\n requests,\n} = require('../tl');\nconst {\n ConnectionTCPObfuscated,\n MTProtoSender,\n UpdateConnectionState,\n} = require('../network');\nconst {\n authFlow,\n checkAuthorization,\n} = require('./auth');\nconst { downloadFile } = require('./downloadFile');\nconst { uploadFile } = require('./uploadFile');\nconst { updateTwoFaSettings } = require('./2fa');\n\nconst DEFAULT_DC_ID = 2;\nconst WEBDOCUMENT_DC_ID = 4;\nconst DEFAULT_IPV4_IP = 'zws2.web.telegram.org';\nconst DEFAULT_IPV6_IP = '[2001:67c:4e8:f002::a]';\nconst EXPORTED_SENDER_RECONNECT_TIMEOUT = 1000; // 1 sec\nconst EXPORTED_SENDER_RELEASE_TIMEOUT = 30000; // 30 sec\nconst WEBDOCUMENT_REQUEST_PART_SIZE = 131072; // 128kb\n\nconst PING_INTERVAL = 3000; // 3 sec\nconst PING_TIMEOUT = 5000; // 5 sec\nconst PING_FAIL_ATTEMPTS = 3;\nconst PING_FAIL_INTERVAL = 100; // ms\n\n// An unusually long interval is a sign of returning from background mode...\nconst PING_INTERVAL_TO_WAKE_UP = 5000; // 5 sec\n// ... so we send a quick \"wake-up\" ping to confirm than connection was dropped ASAP\nconst PING_WAKE_UP_TIMEOUT = 3000; // 3 sec\n// We also send a warning to the user even a bit more quickly\nconst PING_WAKE_UP_WARNING_TIMEOUT = 1000; // 1 sec\n\nconst PING_DISCONNECT_DELAY = 60000; // 1 min\n\n// All types\nconst sizeTypes = ['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._isSwitchingDc = false;\n this._destroyed = false;\n }\n\n // region Connecting\n\n /**\n * Connects to the Telegram servers, executing authentication if required.\n * Note that authenticating to the Telegram servers is not the same as authenticating\n * the app, which requires to send a code first.\n * @returns {Promise}\n */\n async connect() {\n await this._initSession();\n\n if (this._sender === undefined) {\n // only init sender once to avoid multiple loops.\n this._sender = new MTProtoSender(this.session.getAuthKey(), {\n logger: this._log,\n dcId: this.session.dcId,\n retries: this._connectionRetries,\n delay: this._retryDelay,\n autoReconnect: this._autoReconnect,\n connectTimeout: this._timeout,\n authKeyCallback: this._authKeyCallback.bind(this),\n updateCallback: this._handleUpdate.bind(this),\n isMainSender: true,\n });\n }\n // set defaults vars\n this._sender.userDisconnected = false;\n this._sender._user_connected = false;\n this._sender.isReconnecting = false;\n this._sender._disconnected = true;\n\n const connection = new this._connection(\n this.session.serverAddress, this.session.port, this.session.dcId, this._log, this._args.testServers,\n );\n\n const newConnection = await this._sender.connect(connection);\n if (!newConnection) {\n // we're already connected so no need to reset auth key.\n if (!this._loopStarted) {\n this._updateLoop();\n this._loopStarted = true;\n }\n return;\n }\n\n this.session.setAuthKey(this._sender.authKey);\n await this._sender.send(this._initWith(\n new requests.help.GetConfig({}),\n ));\n\n if (!this._loopStarted) {\n this._updateLoop();\n this._loopStarted = true;\n }\n this._isSwitchingDc = false;\n }\n\n async _initSession() {\n await this.session.load();\n\n if (!this.session.serverAddress || (this.session.serverAddress.includes(':') !== this._useIPV6)) {\n this.session.setDC(DEFAULT_DC_ID, this._useIPV6\n ? DEFAULT_IPV6_IP : DEFAULT_IPV4_IP, this._args.useWSS ? 443 : 80);\n }\n }\n\n async _updateLoop() {\n let lastPongAt;\n\n while (!this._destroyed) {\n await Helpers.sleep(PING_INTERVAL);\n if (this._sender.isReconnecting || this._isSwitchingDc) {\n lastPongAt = undefined;\n continue;\n }\n\n try {\n const ping = () => {\n return this._sender.send(new requests.PingDelayDisconnect({\n pingId: Helpers.getRandomInt(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER),\n disconnectDelay: PING_DISCONNECT_DELAY,\n }));\n };\n\n const pingAt = Date.now();\n const lastInterval = lastPongAt ? pingAt - lastPongAt : undefined;\n\n if (!lastInterval || lastInterval < PING_INTERVAL_TO_WAKE_UP) {\n await attempts(() => timeout(ping, PING_TIMEOUT), PING_FAIL_ATTEMPTS, PING_FAIL_INTERVAL);\n } else {\n let wakeUpWarningTimeout = setTimeout(() => {\n this._handleUpdate(new UpdateConnectionState(UpdateConnectionState.disconnected));\n wakeUpWarningTimeout = undefined;\n }, PING_WAKE_UP_WARNING_TIMEOUT);\n\n await timeout(ping, PING_WAKE_UP_TIMEOUT);\n\n if (wakeUpWarningTimeout) {\n clearTimeout(wakeUpWarningTimeout);\n wakeUpWarningTimeout = undefined;\n }\n\n this._handleUpdate(new UpdateConnectionState(UpdateConnectionState.connected));\n }\n\n lastPongAt = Date.now();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n\n lastPongAt = undefined;\n\n if (this._sender.isReconnecting || this._isSwitchingDc) {\n continue;\n }\n\n await this.disconnect();\n await this.connect();\n }\n\n // We need to send some content-related request at least hourly\n // for Telegram to keep delivering updates, otherwise they will\n // just stop even if we're connected. Do so every 30 minutes.\n\n // TODO Call getDifference instead since it's more relevant\n if (new Date().getTime() - this._lastRequest > 30 * 60 * 1000) {\n try {\n await this.invoke(new requests.updates.GetState());\n } catch (e) {\n // we don't care about errors here\n }\n\n lastPongAt = undefined;\n }\n }\n await this.disconnect();\n }\n\n /**\n * Disconnects from the Telegram server\n * @returns {Promise}\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._isSwitchingDc = true;\n await this.disconnect();\n return this.connect();\n }\n\n _authKeyCallback(authKey, dcId) {\n this.session.setAuthKey(authKey, dcId);\n }\n\n // endregion\n // export region\n\n async _cleanupExportedSender(dcId) {\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, Boolean(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 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 async downloadStaticMap(accessHash, long, lat, w, h, zoom, scale, accuracyRadius) {\n try {\n const buff = [];\n let offset = 0;\n while (true) {\n try {\n const downloaded = new requests.upload.GetWebFile({\n location: new constructors.InputWebFileGeoPointLocation({\n geoPoint: new constructors.InputGeoPoint({\n lat,\n long,\n accuracyRadius,\n }),\n accessHash,\n w,\n h,\n zoom,\n scale,\n }),\n offset,\n limit: WEBDOCUMENT_REQUEST_PART_SIZE,\n });\n const sender = await this._borrowExportedSender(WEBDOCUMENT_DC_ID);\n const res = await sender.send(downloaded);\n offset += 131072;\n if (res.bytes.length) {\n buff.push(res.bytes);\n if (res.bytes.length < WEBDOCUMENT_REQUEST_PART_SIZE) {\n break;\n }\n } else {\n break;\n }\n } catch (err) {\n if (err instanceof errors.FloodWaitError) {\n // eslint-disable-next-line no-console\n console.warn(`getWebFile: sleeping for ${err.seconds}s on flood wait`);\n await sleep(err.seconds * 1000);\n continue;\n }\n }\n }\n return Buffer.concat(buff);\n } catch (e) {\n // the file is no longer saved in telegram's cache.\n if (e.message === 'WEBFILE_NOT_AVAILABLE') {\n return Buffer.alloc(0);\n } else {\n throw e;\n }\n }\n }\n\n // region Invoking Telegram request\n /**\n * Invokes a MTProtoRequest (sends and receives it) and returns its result\n * @param request\n * @param dcId Optional dcId to use when sending the request\n * @returns {Promise}\n */\n\n async invoke(request, dcId) {\n if (request.classType !== 'request') {\n throw new Error('You can only invoke MTProtoRequests');\n }\n\n const sender = dcId === undefined ? this._sender : await this.getSender(dcId);\n this._lastRequest = new Date().getTime();\n let attempt = 0;\n for (attempt = 0; attempt < this._requestRetries; attempt++) {\n const promise = sender.sendWithInvokeSupport(request);\n try {\n const result = await promise.promise;\n return result;\n } catch (e) {\n if (e instanceof errors.ServerError || e.message === 'RPC_CALL_FAIL'\n || e.message === 'RPC_MCGET_FAIL') {\n this._log.warn(`Telegram is having internal issues ${e.constructor.name}`);\n await sleep(2000);\n } else if (e instanceof errors.FloodWaitError || e instanceof errors.FloodTestPhoneWaitError) {\n if (e.seconds <= this.floodSleepLimit) {\n this._log.info(`Sleeping for ${e.seconds}s on flood wait`);\n await sleep(e.seconds * 1000);\n } else {\n throw e;\n }\n } else if (e instanceof errors.PhoneMigrateError || e instanceof errors.NetworkMigrateError\n || e instanceof errors.UserMigrateError) {\n this._log.info(`Phone migrated to ${e.newDc}`);\n const shouldRaise = e instanceof errors.PhoneMigrateError\n || e instanceof errors.NetworkMigrateError;\n if (shouldRaise && await checkAuthorization(this)) {\n throw e;\n }\n await this._switchDC(e.newDc);\n } else if (e instanceof errors.MsgWaitError) {\n // we need to resend this after the old one was confirmed.\n await promise.isReady();\n } else {\n throw e;\n }\n }\n }\n throw new Error(`Request was unsuccessful ${attempt} time(s)`);\n }\n\n 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(cb, ms) {\n return Promise.race([\n cb(),\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 @typescript-eslint/return-await\n return await cb();\n } catch (err) {\n if (i === times - 1) {\n throw err;\n }\n\n await Helpers.sleep(pause);\n }\n }\n return undefined;\n}\n\nmodule.exports = TelegramClient;\n","// 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: any) {\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: any) {\n if (err.message === 'RESTART_AUTH_WITH_QR') {\n return signInUserWithQrCode(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n } else {\n phoneNumber = authParams.phoneNumber;\n }\n const sendCodeResult = await sendCode(client, apiCredentials, phoneNumber, authParams.forceSMS);\n phoneCodeHash = sendCodeResult.phoneCodeHash;\n isCodeViaApp = sendCodeResult.isCodeViaApp;\n\n if (typeof phoneCodeHash !== 'string') {\n throw new Error('Failed to retrieve phone code hash');\n }\n\n break;\n } catch (err: any) {\n if (typeof authParams.phoneNumber !== 'function') {\n throw err;\n }\n\n authParams.onError(err);\n }\n }\n\n let phoneCode;\n let isRegistrationRequired = false;\n let termsOfService;\n\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n try {\n phoneCode = await authParams.phoneCode(isCodeViaApp);\n } catch (err: any) {\n // This is the support for changing phone number from the phone code screen.\n if (err.message === 'RESTART_AUTH') {\n return signInUser(client, apiCredentials, authParams);\n }\n }\n\n if (!phoneCode) {\n throw new Error('Code is empty');\n }\n\n // May raise PhoneCodeEmptyError, PhoneCodeExpiredError,\n // PhoneCodeHashEmptyError or PhoneCodeInvalidError.\n const result = await client.invoke(new Api.auth.SignIn({\n phoneNumber,\n phoneCodeHash,\n phoneCode,\n }));\n\n if (result instanceof Api.auth.AuthorizationSignUpRequired) {\n isRegistrationRequired = true;\n termsOfService = result.termsOfService;\n break;\n }\n\n return result.user;\n } catch (err: any) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n } else {\n authParams.onError(err);\n }\n }\n }\n\n if (isRegistrationRequired) {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const [firstName, lastName] = await authParams.firstAndLastNames();\n if (!firstName) {\n throw new Error('First name is required');\n }\n\n const { user } = await client.invoke(new Api.auth.SignUp({\n phoneNumber,\n phoneCodeHash,\n firstName,\n lastName,\n })) as Api.auth.Authorization;\n\n if (termsOfService) {\n // This is a violation of Telegram rules: the user should be presented with and accept TOS.\n await client.invoke(new Api.help.AcceptTermsOfService({ id: termsOfService.id }));\n }\n\n return user;\n } catch (err: any) {\n authParams.onError(err);\n }\n }\n }\n\n authParams.onError(new Error('Auth failed'));\n return signInUser(client, apiCredentials, authParams);\n}\n\nasync function signInUserWithQrCode(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\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: any) {\n if (err.message === 'RESTART_AUTH') {\n return await signInUser(client, apiCredentials, authParams);\n }\n\n throw err;\n } finally {\n isScanningComplete = true;\n }\n\n try {\n const result2 = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n\n if (result2 instanceof Api.auth.LoginTokenSuccess && result2.authorization instanceof Api.auth.Authorization) {\n return result2.authorization.user;\n } else if (result2 instanceof Api.auth.LoginTokenMigrateTo) {\n await client._switchDC(result2.dcId);\n const migratedResult = await client.invoke(new Api.auth.ImportLoginToken({\n token: result2.token,\n }));\n\n if (migratedResult instanceof Api.auth.LoginTokenSuccess\n && migratedResult.authorization instanceof Api.auth.Authorization) {\n return migratedResult.authorization.user;\n }\n }\n } catch (err: any) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n\n // This is a workaround for TypeScript (never actually reached)\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw undefined;\n}\n\nasync function sendCode(\n client: TelegramClient, apiCredentials: ApiCredentials, phoneNumber: string, forceSMS = false,\n): Promise<{\n phoneCodeHash: string;\n isCodeViaApp: boolean;\n }> {\n try {\n const { apiId, apiHash } = apiCredentials;\n const sendResult = await client.invoke(new Api.auth.SendCode({\n phoneNumber,\n apiId,\n apiHash,\n settings: new Api.CodeSettings(),\n }));\n\n // If we already sent a SMS, do not resend the phoneCode (hash may be empty)\n if (!forceSMS || (sendResult.type instanceof Api.auth.SentCodeTypeSms)) {\n return {\n phoneCodeHash: sendResult.phoneCodeHash,\n isCodeViaApp: sendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n }\n\n const resendResult = await client.invoke(new Api.auth.ResendCode({\n phoneNumber,\n phoneCodeHash: sendResult.phoneCodeHash,\n }));\n\n return {\n phoneCodeHash: resendResult.phoneCodeHash,\n isCodeViaApp: resendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n } catch (err: any) {\n if (err.message === 'AUTH_RESTART') {\n return sendCode(client, apiCredentials, phoneNumber, forceSMS);\n } else {\n throw err;\n }\n }\n}\n\nasync function signInWithPassword(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const passwordSrpResult = await client.invoke(new Api.account.GetPassword());\n const password = await authParams.password(passwordSrpResult.hint);\n if (!password) {\n throw new Error('Password is empty');\n }\n\n const passwordSrpCheck = await computePasswordSrpCheck(passwordSrpResult, password);\n const { user } = await client.invoke(new Api.auth.CheckPassword({\n password: passwordSrpCheck,\n })) as Api.auth.Authorization;\n\n return user;\n } catch (err: any) {\n authParams.onError(err);\n }\n }\n\n // eslint-disable-next-line no-unreachable\n return undefined!; // Never reached (TypeScript fix)\n}\n\nasync function signInBot(client: TelegramClient, apiCredentials: ApiCredentials, authParams: BotAuthParams) {\n const { apiId, apiHash } = apiCredentials;\n const { botAuthToken } = authParams;\n\n const { user } = await client.invoke(new Api.auth.ImportBotAuthorization({\n apiId,\n apiHash,\n botAuthToken,\n })) as Api.auth.Authorization;\n\n return user;\n}\n","// 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('./updates');\nconst { BadMessageError } = require('../errors/Common');\nconst {\n BadServerSalt,\n BadMsgNotification,\n MsgDetailedInfo,\n MsgNewDetailedInfo,\n NewSessionCreated,\n FutureSalts,\n MsgsStateReq,\n MsgResendReq,\n MsgsAllInfo,\n} = require('../tl').constructors;\nconst { SecurityError } = require('../errors/Common');\nconst { InvalidBufferError } = require('../errors/Common');\nconst { LogOut } = require('../tl').requests.auth;\nconst { RPCMessageToError } = require('../errors');\nconst { TypeNotFoundError } = require('../errors/Common');\n\n/**\n * MTProto Mobile Protocol sender\n * (https://core.telegram.org/mtproto/description)\n * This class is responsible for wrapping requests into `TLMessage`'s,\n * sending them over the network and receiving them in a safe manner.\n *\n * Automatic reconnection due to temporary network issues is a concern\n * for this class as well, including retry of messages that could not\n * be sent successfully.\n *\n * A new authorization key will be generated on connection if no other\n * key exists yet.\n */\nclass MTProtoSender {\n static DEFAULT_OPTIONS = {\n logger: undefined,\n retries: Infinity,\n delay: 2000,\n autoReconnect: true,\n connectTimeout: undefined,\n authKeyCallback: undefined,\n updateCallback: undefined,\n autoReconnectCallback: undefined,\n isMainSender: undefined,\n onConnectionBreak: undefined,\n };\n\n /**\n * @param authKey\n * @param opts\n */\n constructor(authKey, opts) {\n const args = { ...MTProtoSender.DEFAULT_OPTIONS, ...opts };\n this._connection = undefined;\n this._log = args.logger;\n this._dcId = args.dcId;\n this._retries = args.retries;\n this._delay = args.delay;\n this._autoReconnect = args.autoReconnect;\n this._connectTimeout = args.connectTimeout;\n this._authKeyCallback = args.authKeyCallback;\n this._updateCallback = args.updateCallback;\n this._autoReconnectCallback = args.autoReconnectCallback;\n this._isMainSender = args.isMainSender;\n this._onConnectionBreak = args.onConnectionBreak;\n\n /**\n * whether we disconnected ourself or telegram did it.\n */\n this.userDisconnected = false;\n\n /**\n * Whether the user has explicitly connected or disconnected.\n *\n * If a disconnection happens for any other reason and it\n * was *not* user action then the pending messages won't\n * be cleared but on explicit user disconnection all the\n * pending futures should be cancelled.\n */\n this._user_connected = false;\n this.isReconnecting = false;\n this._disconnected = true;\n\n /**\n * We need to join the loops upon disconnection\n */\n this._send_loop_handle = undefined;\n this._recv_loop_handle = undefined;\n\n /**\n * Preserving the references of the AuthKey and state is important\n */\n this.authKey = authKey || new AuthKey();\n this._state = new MTProtoState(this.authKey, this._log);\n\n /**\n * Outgoing messages are put in a queue and sent in a batch.\n * Note that here we're also storing their ``_RequestState``.\n */\n this._send_queue = new MessagePacker(this._state, this._log);\n\n /**\n * Sent states are remembered until a response is received.\n */\n this._pending_state = {};\n\n /**\n * Responses must be acknowledged, and we can also batch these.\n */\n this._pending_ack = new Set();\n\n /**\n * Similar to pending_messages but only for the last acknowledges.\n * These can't go in pending_messages because no acknowledge for them\n * is received, but we may still need to resend their state on bad salts.\n */\n this._last_acks = [];\n\n /**\n * Jump table from response ID to method that handles it\n */\n\n this._handlers = {\n [RPCResult.CONSTRUCTOR_ID]: this._handleRPCResult.bind(this),\n [MessageContainer.CONSTRUCTOR_ID]: this._handleContainer.bind(this),\n [GZIPPacked.CONSTRUCTOR_ID]: this._handleGzipPacked.bind(this),\n [Pong.CONSTRUCTOR_ID]: this._handlePong.bind(this),\n [BadServerSalt.CONSTRUCTOR_ID]: this._handleBadServerSalt.bind(this),\n [BadMsgNotification.CONSTRUCTOR_ID]: this._handleBadNotification.bind(this),\n [MsgDetailedInfo.CONSTRUCTOR_ID]: this._handleDetailedInfo.bind(this),\n [MsgNewDetailedInfo.CONSTRUCTOR_ID]: this._handleNewDetailedInfo.bind(this),\n [NewSessionCreated.CONSTRUCTOR_ID]: this._handleNewSessionCreated.bind(this),\n [MsgsAck.CONSTRUCTOR_ID]: this._handleAck.bind(this),\n [FutureSalts.CONSTRUCTOR_ID]: this._handleFutureSalts.bind(this),\n [MsgsStateReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgResendReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgsAllInfo.CONSTRUCTOR_ID]: this._handleMsgAll.bind(this),\n };\n }\n\n // Public API\n\n /**\n * Connects to the specified given connection using the given auth key.\n * @param connection\n * @param [force]\n * @returns {Promise}\n */\n async connect(connection, force) {\n this.userDisconnected = false;\n\n if (this._user_connected && !force) {\n this._log.info('User is already connected!');\n return false;\n }\n this.isConnecting = true;\n this._connection = connection;\n\n for (let attempt = 0; attempt < this._retries; attempt++) {\n try {\n await this._connect();\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.connected));\n }\n break;\n } catch (err) {\n if (this._updateCallback && attempt === 0) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n this._log.error(`WebSocket connection failed attempt: ${attempt + 1}`);\n // eslint-disable-next-line no-console\n console.error(err);\n await Helpers.sleep(this._delay);\n }\n }\n this.isConnecting = false;\n return true;\n }\n\n isConnected() {\n return this._user_connected;\n }\n\n /**\n * Cleanly disconnects the instance from the network, cancels\n * all pending requests, and closes the send and receive loops.\n */\n async disconnect() {\n this.userDisconnected = true;\n await this._disconnect();\n }\n\n /**\n *\n This method enqueues the given request to be sent. Its send\n state will be saved until a response arrives, and a ``Future``\n that will be resolved when the response arrives will be returned:\n\n .. code-block:: javascript\n\n async def method():\n # Sending (enqueued for the send loop)\n future = sender.send(request)\n # Receiving (waits for the receive loop to read the result)\n result = await future\n\n Designed like this because Telegram may send the response at\n any point, and it can send other items while one waits for it.\n Once the response for this future arrives, it is set with the\n received result, quite similar to how a ``receive()`` call\n would otherwise work.\n\n Since the receiving part is \"built in\" the future, it's\n impossible to await receive a result that was never sent.\n * @param request\n * @returns {RequestState}\n */\n send(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected');\n }\n const state = new RequestState(request);\n this._send_queue.append(state);\n return state.promise;\n }\n\n /**\n * Same as send but returns the full state. usefull for invoke after logic\n * @param request\n * @return {RequestState}\n */\n sendWithInvokeSupport(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected');\n }\n const state = new RequestState(request, undefined, this._pending_state);\n this._send_queue.append(state);\n return state;\n }\n\n /**\n * Performs the actual connection, retrying, generating the\n * authorization key if necessary, and starting the send and\n * receive loops.\n * @returns {Promise}\n * @private\n */\n async _connect() {\n this._log.info('Connecting to {0}...'.replace('{0}', this._connection));\n await this._connection.connect();\n this._log.debug('Connection success!');\n // process.exit(0)\n if (!this.authKey.getKey()) {\n const plain = new MtProtoPlainSender(this._connection, this._log);\n this._log.debug('New auth_key attempt ...');\n const res = await doAuthentication(plain, this._log);\n this._log.debug('Generated new auth_key successfully');\n await this.authKey.setKey(res.authKey);\n\n this._state.timeOffset = res.timeOffset;\n\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(this._state.timeOffset));\n }\n\n /**\n * This is *EXTREMELY* important since we don't control\n * external references to the authorization key, we must\n * notify whenever we change it. This is crucial when we\n * switch to different data centers.\n */\n if (this._authKeyCallback) {\n await this._authKeyCallback(this.authKey, this._dcId);\n }\n } else {\n this._authenticated = true;\n this._log.debug('Already have an auth key ...');\n }\n this._user_connected = true;\n this.isReconnecting = false;\n\n this._log.debug('Starting send loop');\n this._send_loop_handle = this._sendLoop();\n\n this._log.debug('Starting receive loop');\n this._recv_loop_handle = this._recvLoop();\n\n // _disconnected only completes after manual disconnection\n // or errors after which the sender cannot continue such\n // as failing to reconnect or any unexpected error.\n\n this._log.info('Connection to %s complete!'.replace('%s', this._connection.toString()));\n }\n\n async _disconnect() {\n this._send_queue.rejectAll();\n\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n\n if (this._connection === undefined) {\n this._log.info('Not disconnecting (already have no connection)');\n return;\n }\n\n this._log.info('Disconnecting from %s...'.replace('%s', this._connection.toString()));\n this._user_connected = false;\n this._log.debug('Closing current connection...');\n await this._connection.disconnect();\n }\n\n /**\n * This loop is responsible for popping items off the send\n * queue, encrypting them, and sending them over the network.\n * Besides `connect`, only this method ever sends data.\n * @returns {Promise}\n * @private\n */\n async _sendLoop() {\n this._send_queue = new MessagePacker(this._state, this._log);\n\n while (this._user_connected && !this.isReconnecting) {\n if (this._pending_ack.size) {\n const ack = new RequestState(new MsgsAck({ msgIds: Array(...this._pending_ack) }));\n this._send_queue.append(ack);\n this._last_acks.push(ack);\n if (this._last_acks.length >= 10) {\n this._last_acks.shift();\n }\n this._pending_ack.clear();\n }\n this._log.debug(`Waiting for messages to send...${this.isReconnecting}`);\n // TODO Wait for the connection send queue to be empty?\n // This means that while it's not empty we can wait for\n // more messages to be added to the send queue.\n const res = await this._send_queue.get();\n\n if (this.isReconnecting) {\n return;\n }\n\n if (!res) {\n continue;\n }\n let { data } = res;\n const { batch } = res;\n this._log.debug(`Encrypting ${batch.length} message(s) in ${data.length} bytes for sending`);\n\n data = await this._state.encryptMessageData(data);\n\n try {\n await this._connection.send(data);\n } catch (e) {\n this._log.error(e);\n this._log.info('Connection closed while sending data');\n return;\n }\n for (const state of batch) {\n if (!Array.isArray(state)) {\n if (state.request.classType === 'request') {\n this._pending_state[state.msgId] = state;\n }\n } else {\n for (const s of state) {\n if (s.request.classType === 'request') {\n this._pending_state[s.msgId] = s;\n }\n }\n }\n }\n this._log.debug('Encrypted messages put in a queue to be sent');\n }\n }\n\n async _recvLoop() {\n let body;\n let message;\n\n while (this._user_connected && !this.isReconnecting) {\n // this._log.debug('Receiving items from the network...');\n this._log.debug('Receiving items from the network...');\n try {\n body = await this._connection.recv();\n } catch (e) {\n // this._log.info('Connection closed while receiving data');\n /** when the server disconnects us we want to reconnect */\n if (!this.userDisconnected) {\n this._log.error(e);\n this._log.warn('Connection closed while receiving data');\n this.reconnect();\n }\n return;\n }\n try {\n message = await this._state.decryptMessageData(body);\n } catch (e) {\n if (e instanceof TypeNotFoundError) {\n // Received object which we don't know how to deserialize\n this._log.info(`Type ${e.invalidConstructorId} not found, remaining data ${e.remaining}`);\n continue;\n } else if (e instanceof SecurityError) {\n // A step while decoding had the incorrect data. This message\n // should not be considered safe and it should be ignored.\n this._log.warn(`Security error while unpacking a received message: ${e}`);\n continue;\n } else if (e instanceof InvalidBufferError) {\n // 404 means that the server has \"forgotten\" our auth key and we need to create a new one.\n if (e.code === 404) {\n this._handleBadAuthKey();\n } else {\n // this happens sometimes when telegram is having some internal issues.\n // reconnecting should be enough usually\n // since the data we sent and received is probably wrong now.\n this._log.warn(`Invalid buffer ${e.code} for dc ${this._dcId}`);\n this.reconnect();\n }\n return;\n } else {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n this.reconnect();\n return;\n }\n }\n try {\n await this._processMessage(message);\n } catch (e) {\n // `RPCError` errors except for 'AUTH_KEY_UNREGISTERED' should be handled by the client\n if (e instanceof RPCError) {\n if (e.message === 'AUTH_KEY_UNREGISTERED') {\n // 'AUTH_KEY_UNREGISTERED' for the main sender is thrown when unauthorized and should be ignored\n this._handleBadAuthKey(true);\n }\n } else {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n }\n }\n }\n }\n\n _handleBadAuthKey(shouldSkipForMain) {\n if (shouldSkipForMain && this._isMainSender) {\n return;\n }\n\n this._log.warn(`Broken authorization key for dc ${this._dcId}, resetting...`);\n\n if (this._isMainSender && this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.broken));\n } else if (!this._isMainSender && this._onConnectionBreak) {\n this._onConnectionBreak(this._dcId);\n }\n }\n\n // Response Handlers\n\n /**\n * Adds the given message to the list of messages that must be\n * acknowledged and dispatches control to different ``_handle_*``\n * method based on its type.\n * @param message\n * @returns {Promise}\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.isReconnecting) {\n this.isReconnecting = true;\n // TODO Should we set this?\n // this._user_connected = false\n // we want to wait a second between each reconnect try to not flood the server with reconnects\n // in case of internal server issues.\n Helpers.sleep(1000)\n .then(() => {\n this._log.info('Started reconnecting');\n this._reconnect();\n });\n }\n }\n\n async _reconnect() {\n this._log.debug('Closing current connection...');\n try {\n await this._disconnect();\n } catch (err) {\n this._log.warn(err);\n }\n\n this._send_queue.append(undefined);\n this._state.reset();\n\n // For some reason reusing existing connection caused stuck requests\n const newConnection = new this._connection.constructor(\n this._connection._ip,\n this._connection._port,\n this._connection._dcId,\n this._connection._log,\n this._connection._testServers,\n );\n await this.connect(newConnection, true);\n\n this.isReconnecting = false;\n // uncomment this if you want to resend\n // this._send_queue.extend(Object.values(this._pending_state))\n for (const state of Object.values(this._pending_state)) {\n state.deferred.resolve();\n }\n this._pending_state = {};\n if (this._autoReconnectCallback) {\n await this._autoReconnectCallback();\n }\n }\n}\n\nmodule.exports = MTProtoSender;\n","const BigInt = require('big-integer');\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\nconst {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n} = require('./connection');\n\nconst {\n UpdateConnectionState,\n UpdateServerTimeOffset,\n} = require('./updates');\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n MTProtoPlainSender,\n MTProtoSender,\n UpdateConnectionState,\n UpdateServerTimeOffset,\n};\n","class UpdateConnectionState {\n static disconnected = -1;\n\n static connected = 1;\n\n static broken = 0;\n\n constructor(state, origin) {\n this.state = state;\n this.origin = origin;\n }\n}\n\nclass UpdateServerTimeOffset {\n constructor(timeOffset) {\n this.timeOffset = timeOffset;\n }\n}\n\nmodule.exports = {\n UpdateConnectionState,\n UpdateServerTimeOffset,\n};\n","class Session {\n /**\n * Creates a clone of this session file\n * @param toInstance {Session|null}\n * @returns {Session}\n */\n\n /* CONTEST\n clone(toInstance = null) {\n return toInstance || new this.constructor()\n } */\n\n /**\n * Returns the currently-used data center ID.\n */\n get dcId() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns the server address where the library should connect to.\n */\n get serverAddress() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns the port to which the library should connect to.\n */\n get port() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns an ``AuthKey`` instance associated with the saved\n * data center, or `None` if a new one should be generated.\n */\n get authKey() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Sets the ``AuthKey`` to be used for the saved data center.\n * @param value\n */\n set authKey(value) {\n throw new Error('Not Implemented');\n }\n\n /**\n * Sets the information of the data center address and port that\n * the library should connect to, as well as the data center ID,\n * which is currently unused.\n * @param dcId {number}\n * @param serverAddress {string}\n * @param port {number}\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setDC(dcId, serverAddress, port) {\n throw new Error('Not implemented');\n }\n\n /**\n * Returns an ID of the takeout process initialized for this session,\n * or `None` if there's no were any unfinished takeout requests.\n */\n /* CONTEST\n get takeoutId() {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Sets the ID of the unfinished takeout process for this session.\n * @param value\n */\n /* CONTEST\n set takeoutId(value) {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Returns the ``UpdateState`` associated with the given `entity_id`.\n * If the `entity_id` is 0, it should return the ``UpdateState`` for\n * no specific channel (the \"general\" state). If no state is known\n * it should ``return None``.\n * @param entityId\n */\n /* CONTEST\n getUpdateState(entityId) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Sets the given ``UpdateState`` for the specified `entity_id`, which\n * should be 0 if the ``UpdateState`` is the \"general\" state (and not\n * for any specific channel).\n * @param entityId\n * @param state\n */\n /* CONTEST\n setUpdateState(entityId, state) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Called on client disconnection. Should be used to\n * free any used resources. Can be left empty if none.\n */\n\n /* CONTEST\n close() {\n\n }\n\n */\n\n /**\n * called whenever important properties change. It should\n * make persist the relevant session information to disk.\n */\n save() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Called upon client.log_out(). Should delete the stored\n * information from disk since it's not valid anymore.\n */\n\n delete() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Lists available sessions. Not used by the library itself.\n */\n /* CONTEST\n listSessions() {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Processes the input ``TLObject`` or ``list`` and saves\n * whatever information is relevant (e.g., ID or access hash).\n * @param tlo\n */\n /* CONTEST\n processEntities(tlo) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Turns the given key into an ``InputPeer`` (e.g. ``InputPeerUser``).\n * The library uses this method whenever an ``InputPeer`` is needed\n * to suit several purposes (e.g. user only provided its ID or wishes\n * to use a cached username to avoid extra RPC).\n */\n /* CONTEST\n getInputEntity(key) {\n throw new Error('Not Implemented')\n }\n\n */\n}\n\nmodule.exports = Session;\n","/* eslint-disable no-restricted-globals */\nconst StorageSession = require('./StorageSession');\n\nconst CACHE_NAME = 'GramJs';\n\nclass CacheApiSession extends StorageSession {\n async _delete() {\n const request = new Request(this._storageKey);\n const cache = await self.caches.open(CACHE_NAME);\n return cache.delete(request);\n }\n\n async _fetchFromCache() {\n const request = new Request(this._storageKey);\n const cache = await self.caches.open(CACHE_NAME);\n const cached = await cache.match(request);\n return cached ? cached.text() : undefined;\n }\n\n async _saveToCache(data) {\n const request = new Request(this._storageKey);\n const response = new Response(data);\n const cache = await self.caches.open(CACHE_NAME);\n return cache.put(request, response);\n }\n}\n\nmodule.exports = CacheApiSession;\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst utils = require('../Utils');\n\nclass CallbackSession extends MemorySession {\n constructor(sessionData, callback) {\n super();\n\n this._sessionData = sessionData;\n this._callback = callback;\n\n this._authKeys = {};\n }\n\n get authKey() {\n throw new Error('Not supported');\n }\n\n set authKey(value) {\n throw new Error('Not supported');\n }\n\n async load() {\n if (!this._sessionData) {\n return;\n }\n\n const {\n mainDcId,\n keys,\n hashes,\n } = this._sessionData;\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n\n this.setDC(mainDcId, ipAddress, port, true);\n\n await Promise.all(Object.keys(keys)\n .map(async (dcId) => {\n const key = typeof keys[dcId] === 'string'\n ? Buffer.from(keys[dcId], 'hex')\n : Buffer.from(keys[dcId]);\n\n if (hashes[dcId]) {\n const hash = typeof hashes[dcId] === 'string'\n ? Buffer.from(hashes[dcId], 'hex')\n : Buffer.from(hashes[dcId]);\n\n this._authKeys[dcId] = new AuthKey(key, hash);\n } else {\n this._authKeys[dcId] = new AuthKey();\n await this._authKeys[dcId].setKey(key, true);\n }\n }));\n }\n\n setDC(dcId, serverAddress, port, skipOnUpdate = false) {\n this._dcId = dcId;\n this._serverAddress = serverAddress;\n this._port = port;\n\n delete this._authKeys[dcId];\n\n if (!skipOnUpdate) {\n void this._onUpdate();\n }\n }\n\n getAuthKey(dcId = this._dcId) {\n return this._authKeys[dcId];\n }\n\n setAuthKey(authKey, dcId = this._dcId) {\n this._authKeys[dcId] = authKey;\n\n void this._onUpdate();\n }\n\n getSessionData() {\n const sessionData = {\n mainDcId: this._dcId,\n keys: {},\n hashes: {},\n };\n\n Object\n .keys(this._authKeys)\n .forEach((dcId) => {\n const authKey = this._authKeys[dcId];\n if (!authKey || !authKey._key) return;\n\n sessionData.keys[dcId] = authKey._key.toString('hex');\n sessionData.hashes[dcId] = authKey._hash.toString('hex');\n });\n\n return sessionData;\n }\n\n _onUpdate() {\n this._callback(this.getSessionData());\n }\n\n delete() {\n this._callback(undefined);\n }\n}\n\nmodule.exports = CallbackSession;\n","const idb = require('idb-keyval');\nconst StorageSession = require('./StorageSession');\n\nconst CACHE_NAME = 'GramJs';\n\nclass IdbSession extends StorageSession {\n _delete() {\n return idb.del(`${CACHE_NAME}:${this._storageKey}`);\n }\n\n _fetchFromCache() {\n return idb.get(`${CACHE_NAME}:${this._storageKey}`);\n }\n\n _saveToCache(data) {\n return idb.set(`${CACHE_NAME}:${this._storageKey}`, data);\n }\n}\n\nmodule.exports = IdbSession;\n","const StorageSession = require('./StorageSession');\n\nclass LocalStorageSession extends StorageSession {\n _delete() {\n return localStorage.removeItem(this._storageKey);\n }\n\n _fetchFromCache() {\n return localStorage.getItem(this._storageKey);\n }\n\n _saveToCache(data) {\n return localStorage.setItem(this._storageKey, data);\n }\n}\n\nmodule.exports = LocalStorageSession;\n","const Session = require('./Abstract');\n\nclass MemorySession extends Session {\n constructor() {\n super();\n\n this._serverAddress = undefined;\n this._dcId = 0;\n this._port = undefined;\n this._takeoutId = undefined;\n\n this._entities = new Set();\n this._updateStates = {};\n }\n\n get dcId() {\n return this._dcId;\n }\n\n get serverAddress() {\n return this._serverAddress;\n }\n\n get port() {\n return this._port;\n }\n\n get authKey() {\n return this._authKey;\n }\n\n set authKey(value) {\n this._authKey = value;\n }\n\n setDC(dcId, serverAddress, port) {\n this._dcId = dcId | 0;\n this._serverAddress = serverAddress;\n this._port = port;\n }\n\n /* CONTEST\n get takeoutId() {\n return this._takeoutId\n }\n\n set takeoutId(value) {\n this._takeoutId = value\n }\n\n\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 = 139;\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#a8edd0f5 flags:# pinned:flags.2?true unread_mark:flags.3?true peer:Peer top_message:int read_inbox_max_id:int read_outbox_max_id:int unread_count:int unread_mentions_count:int unread_reactions_count:int notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?int = Dialog;\ndialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog;\nphotoEmpty#2331b22d id:long = Photo;\nphoto#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector 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;\ninputReportReasonIllegalDrugs#a8eb2be = ReportReason;\ninputReportReasonPersonalDetails#9ec7863d = 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 videos:flags.6?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 rtmp_stream:flags.12?true listeners_hidden:flags.13?true id:long access_hash:long participants_count:int title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int unmuted_video_count:flags.10?int unmuted_video_limit:int version:int = GroupCall;\ninputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall;\ngroupCallParticipant#eba636fe flags:# muted:flags.0?true left:flags.1?true can_self_unmute:flags.2?true just_joined:flags.4?true versioned:flags.5?true min:flags.8?true muted_by_you:flags.9?true volume_by_admin:flags.10?true self:flags.12?true video_joined:flags.15?true peer:Peer date:int active_date:flags.3?int source:int volume:flags.7?int about:flags.11?string raise_hand_rating:flags.13?long video:flags.6?GroupCallParticipantVideo presentation:flags.14?GroupCallParticipantVideo = GroupCallParticipant;\nphone.groupCall#9e727aad call:GroupCall participants:Vector 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#4f2b9479 flags:# min:flags.0?true can_see_list:flags.2?true results:Vector recent_reactions:flags.1?Vector = MessageReactions;\nmessages.messageReactionsList#31bd492d flags:# count:int reactions:Vector chats:Vector users:Vector next_offset:flags.0?string = messages.MessageReactionsList;\navailableReaction#c077ec01 flags:# inactive:flags.0?true reaction:string title:string static_icon:Document appear_animation:Document select_animation:Document activate_animation:Document effect_animation:Document around_animation:flags.1?Document center_icon:flags.1?Document = AvailableReaction;\nmessages.availableReactionsNotModified#9f071957 = messages.AvailableReactions;\nmessages.availableReactions#768e3aad hash:int reactions:Vector = messages.AvailableReactions;\nmessages.translateNoResult#67ca4737 = messages.TranslatedText;\nmessages.translateResultText#a214f7d0 text:string = messages.TranslatedText;\nmessagePeerReaction#51b67eff flags:# big:flags.0?true unread:flags.1?true peer_id:Peer reaction:string = MessagePeerReaction;\ngroupCallStreamChannel#80eb48af channel:int scale:int last_timestamp_ms:long = GroupCallStreamChannel;\nphone.groupCallStreamChannels#d0e482b2 channels:Vector = phone.GroupCallStreamChannels;\nphone.groupCallStreamRtmpUrl#2dbf3432 url:string key:string = phone.GroupCallStreamRtmpUrl;\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;\ncontacts.resolvePhone#8af94344 phone:string = contacts.ResolvedPeer;\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.reportSpam#cf1592db peer:InputPeer = Bool;\nmessages.getPeerSettings#efd9a6a2 peer:InputPeer = messages.PeerSettings;\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.saveGif#327a30cb id:InputDocument unsave:Bool = Bool;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\nmessages.sendInlineBotResult#7aa11297 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true hide_via:flags.11?true peer:InputPeer reply_to_msg_id:flags.0?int random_id:long query_id:long id:string schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.editMessage#48f71778 flags:# no_webpage:flags.1?true peer:InputPeer id:int message:flags.11?string media:flags.14?InputMedia reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector 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.hidePeerSettingsBar#4facb138 peer:InputPeer = Bool;\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.getExportedChatInvites#a2b5a3f6 flags:# revoked:flags.3?true peer:InputPeer admin_id:InputUser offset_date:flags.2?int offset_link:flags.2?string limit:int = messages.ExportedChatInvites;\nmessages.editExportedChatInvite#bdca2f75 flags:# revoked:flags.2?true peer:InputPeer link:string expire_date:flags.0?int usage_limit:flags.1?int request_needed:flags.3?Bool title:flags.4?string = messages.ExportedChatInvite;\nmessages.deleteRevokedExportedChatInvites#56987bd5 peer:InputPeer admin_id:InputUser = Bool;\nmessages.deleteExportedChatInvite#d464a42b peer:InputPeer link:string = Bool;\nmessages.getChatInviteImporters#df04dd4e flags:# requested:flags.0?true peer:InputPeer link:flags.1?string q:flags.2?string offset_date:int offset_user:InputUser limit:int = messages.ChatInviteImporters;\nmessages.getMessageReadParticipants#2c6f97b7 peer:InputPeer msg_id:int = Vector;\nmessages.hideChatJoinRequest#7fe7e815 flags:# approved:flags.0?true peer:InputPeer user_id:InputUser = Updates;\nmessages.hideAllChatJoinRequests#e085f4ea flags:# approved:flags.0?true peer:InputPeer link:flags.1?string = Updates;\nmessages.toggleNoForwards#b11eafa2 peer:InputPeer enabled:Bool = Updates;\nmessages.saveDefaultSendAs#ccfddf96 peer:InputPeer send_as:InputPeer = Bool;\nmessages.sendReaction#25690ce4 flags:# big:flags.1?true peer:InputPeer msg_id:int reaction:flags.0?string = Updates;\nmessages.getMessagesReactions#8bba90e6 peer:InputPeer id:Vector = Updates;\nmessages.getMessageReactionsList#e0ee6b77 flags:# peer:InputPeer id:int reaction:flags.0?string offset:flags.1?string limit:int = messages.MessageReactionsList;\nmessages.setChatAvailableReactions#14050ea6 peer:InputPeer available_reactions:Vector = Updates;\nmessages.getAvailableReactions#18dea0ac hash:int = messages.AvailableReactions;\nmessages.setDefaultReaction#d960c4d4 reaction:string = 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.getAppConfig#98914110 = JSONValue;\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:# rtmp_stream:flags.2?true peer:InputPeer random_id:int title:flags.0?string schedule_date:flags.1?int = Updates;\nphone.joinGroupCall#b132ff7b flags:# muted:flags.0?true video_stopped:flags.2?true call:InputGroupCall join_as:InputPeer invite_hash:flags.1?string params:DataJSON = Updates;\nphone.leaveGroupCall#500377f9 call:InputGroupCall source:int = Updates;\nphone.discardGroupCall#7a777135 call:InputGroupCall = Updates;\nphone.getGroupCall#41845db call:InputGroupCall limit:int = phone.GroupCall;\nphone.getGroupParticipants#c558d8ab call:InputGroupCall ids:Vector 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;\nstats.getBroadcastStats#ab42441a flags:# dark:flags.0?true channel:InputChannel = stats.BroadcastStats;\nstats.loadAsyncGraph#621d5fa0 flags:# token:string x:flags.0?long = StatsGraph;\nstats.getMegagroupStats#dcdf8607 flags:# dark:flags.0?true channel:InputChannel = stats.MegagroupStats;`;","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 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 const vectorMatch = currentConfig.type.match(/[Vv]ector<([\\w\\d.]+)>/);\n\n if (vectorMatch) {\n currentConfig.isVector = true;\n\n // If the type's first letter is not uppercase, then\n // it is a constructor and we use (read/write) its ID.\n currentConfig.useVectorId = currentConfig.type.charAt(0) === 'V';\n\n // Update the type to match the one inside the vector\n [, currentConfig.type] = vectorMatch;\n }\n\n // See use_vector_id. An example of such case is ipPort in\n // help.configSpecial\n if (/^[a-z]$/.test(currentConfig.type.split('.')\n .pop()\n .charAt(0))\n ) {\n currentConfig.skipConstructorId = true;\n }\n\n // The name may contain \"date\" in it, if this is the case and\n // the type is \"int\", we can safely assume that this should be\n // treated as a \"date\" object. Note that this is not a valid\n // Telegram object, but it's easier to work with\n // if (\n // this.type === 'int' &&\n // (/(\\b|_)([dr]ate|until|since)(\\b|_)/.test(name) ||\n // ['expires', 'expires_at', 'was_online'].includes(name))\n // ) {\n // this.type = 'date';\n // }\n }\n return currentConfig;\n}\n\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, [802,313], () => (__webpack_require__(1742)))\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 + \".\" + {\"313\":\"5cd1718104a79212da23\",\"802\":\"acd83f1b28a8893b9dba\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks and sibling chunks for the entrypoint\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","var scriptUrl;\nif (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + \"\";\nvar document = __webpack_require__.g.document;\nif (!scriptUrl && document) {\n\tif (document.currentScript)\n\t\tscriptUrl = document.currentScript.src\n\tif (!scriptUrl) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tif(scripts.length) scriptUrl = scripts[scripts.length - 1].src\n\t}\n}\n// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration\n// or pass an empty string (\"\") and set the __webpack_public_path__ variable from your code to use your own logic.\nif (!scriptUrl) throw new Error(\"Automatic publicPath is not supported in this browser\");\nscriptUrl = scriptUrl.replace(/#.*$/, \"\").replace(/\\?.*$/, \"\").replace(/\\/[^\\/]+$/, \"/\");\n__webpack_require__.p = scriptUrl;","// no baseURI\n\n// object to store loaded chunks\n// \"1\" means \"already loaded\"\nvar installedChunks = {\n\t742: 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","prefix","btoa","String","fromCharCode","omitVirtualClassFields","instance","flags","CONSTRUCTOR_ID","SUBCLASS_OF_ID","className","classType","getBytes","rest","pathBytesToSvg","width","height","replace","path","len","length","i","num","buildPath","DEFAULT_THUMB_SIZE","w","h","buildApiThumbnailFromStripped","sizes","thumb","find","s","GramJs","realSizes","filter","dataUri","strippedPhotoToJpg","undefined","buildApiPhoto","photo","map","buildApiPhotoSize","id","thumbnail","photoSize","type","localMessages","chats","users","messages","documents","stickerSets","photos","webDocuments","LOTTIE_STICKER_MIME_TYPE","VIDEO_STICKER_MIME_TYPE","buildStickerFromDocument","document","stickerAttribute","attributes","attr","fileAttribute","isLottie","isVideo","imageSizeAttribute","videoSizeAttribute","sizeAttribute","stickerSetInfo","stickerset","emoji","alt","cachedThumb","thumbs","self","isWebmSupported","pathThumb","buildApiThumbnailFromCached","buildApiThumbnailFromPath","stickerSetId","stickerSetAccessHash","accessHash","buildStickerSet","set","archived","animated","installedDate","videos","title","count","shortName","isVideos","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","Spoiler","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","buildMessageContent","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","sticker","shouldHideKeyboardButtons","views","isFromScheduled","fromScheduled","reactions","buildMessageReactions","replyToMessageId","replyToChatId","replyToTopMessageId","mentioned","hasUnreadMention","isMentioned","viaBotId","comments","threadInfo","buildThreadInfo","noforwards","isProtected","recentReactions","results","canSeeList","buildReactionCount","buildMessagePeerReaction","reactionCount","chosen","reaction","isChosen","userReaction","buildApiAvailableReaction","availableReaction","selectAnimation","staticIcon","inactive","aroundAnimation","centerIcon","buildApiDocument","isInactive","buildMessageMediaContent","poll","contact","isRound","buildApiMessageEntity","buildMessageDraft","draft","formattedText","replyingToId","ttlSeconds","buildSticker","buildPhoto","buildVideoFromDocument","buildVideo","audioAttribute","voice","thumbnailSizes","fileName","getFilenameFromDocument","buildAudio","waveform","buildVoice","buildDocumentFromMedia","phoneNumber","buildContact","buildPoll","buildPollFromMedia","webPage","buildWebPage","invoice","description","test","photoUrl","isTest","buildInvoice","buildInvoiceFromMedia","location","point","buildGeoPoint","geo","buildGeo","provider","address","venueId","venueType","buildVenue","period","heading","buildGeoLive","buildLocationFromMedia","size","isMovSupported","videoAttr","a","gifAttr","supportsStreaming","roundMessage","isGif","mediaType","mediaSize","has","imageAttribute","timestamp","long","lat","accuracyRadius","pollResults","answers","rawAnswers","answer","option","summary","isPublic","publicVoters","buildPollResults","rawResults","totalVoters","recentVoters","solution","solutionEntities","correct","voters","isCorrect","votersCount","recentVoterIds","defaultBase","filenameAttribute","extension","split","buildUploadingMedia","attachment","filename","blobUrl","previewBlobUrl","quick","inputWaveform","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","emoticon","buildApiChatFolder","channels","broadcasts","pinnedChatIds","pinnedPeers","includedChatIds","includePeers","excludedChatIds","excludePeers","buildApiChatFolderFromSuggested","buildApiChatBotCommands","botInfos","botCommands","botInfo","botId","concat","commands","mtpCommand","buildApiExportedInvite","invite","revoked","expireDate","link","permanent","startDate","usage","usageLimit","requested","requestNeeded","adminId","isRevoked","isPermanent","isRequestNeeded","buildApiChatSettings","autoarchived","reportSpam","addContact","blockContact","isAutoArchived","canReportSpam","canAddContact","canBlockContact","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","buildJson","json","acc","el","buildApiGroupCallParticipant","participant","versioned","canSelfUnmute","justJoined","muted","mutedByYou","source","volume","volumeByAdmin","videoJoined","presentation","raiseHandRating","isLeft","isMutedByMe","hasJustJoined","isVolumeByAdmin","isVersioned","isVideoJoined","isUser","buildApiGroupCallParticipantVideo","participantVideo","audioSource","endpoint","paused","sourceGroups","isPaused","buildApiGroupCallParticipantVideoSourceGroup","participantVideoSourceGroup","semantics","sources","buildApiGroupCall","connectionState","version","streamDcId","scheduleDate","canChangeJoinMuted","joinMuted","canStartVideo","scheduleStartSubscribed","isLoaded","onUpdate","sentMessageIds","shouldIgnoreNextChannelUpdate","dispatchUserAndChatUpdates","e","updater","originRequest","connection","timeOffset","state","shouldForceReply","buildApiMessageFromShort","selective","_entities","dcId","buildChatPhotoForLocalDb","localDbChatId","newProfilePhoto","some","msgId","ids","existingIds","missingIds","profilePhotoIds","setTimeout","popup","error","notification","currentDate","inboxDate","buildApiMessageFromNotification","localMessage","Error","newContent","add","isAlreadySent","isScheduled","sendingState","messageUpdate","pollId","apiPoll","pollUpdate","options","stillUnreadCount","isPinned","pinned","order","dp","folderPeers","folderPeer","folder","orderedIds","replacedMembers","addedMember","deletedMemberId","messageIds","interaction","JSON","parse","timestamps","l","t","typingStatus","channel","unread","apiUserId","updatedUser","settings","peerType","buildPrivacyKey","params","groupCallId","recentRequesterIds","recentRequesters","requestsPending","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","console","warn","save","cacheData","stringify","Response","put","clear","delete","MEDIA_ENTITY_TYPES","getMimeType","fallbackMimeType","signature","subarray","byte","GramJsLogger","gramJsUpdateEventBuilder","build","client","isConnected","destroy","invokeRequest","disconnect","onSessionUpdate","sessionData","handleGramJsUpdate","handleTerminatedSession","shouldReturnTrue","shouldThrow","shouldIgnoreUpdates","invoke","handleUpdatesFromRequest","dispatchErrorUpdate","manyUpdates","singleUpdate","updates","injectUpdateEntities","downloadMedia","args","onProgress","mediaFormat","start","end","fullSize","mediaMatch","arrayBuffer","entityType","entityId","sizeType","parsedParams","URLSearchParams","zoom","scale","downloadStaticMap","Stream","acceptsBuffer","progressCallback","workers","getMessageMediaMimeType","downloadStickerSetThumb","Lottie","downloadProfilePhoto","download","parsed","BlobUrl","Progressive","buffer","parseMedia","canCache","prepared","mediaData","URL","createObjectURL","downloadMediaWithClient","uploadFile","file","updateTwoFaSettings","fetchCurrentUser","userFull","currentUser","_currentUserId","onCurrentUserUpdate","isSlowMode","hasErrorKey","MAX_INT_32","fetchChats","limit","offsetDate","withPinned","lastLocalServiceMessage","offsetPeer","excludePinned","resultPinned","updateLocalDb","lastMessagesByChatId","peersByKey","preparePeers","draftsById","replyingToById","dialogs","orderedPinnedIds","lastMessage","isListed","chatIds","totalChatCount","fetchFullChat","fullChat","onlineCount","exportedInvite","slowmodeSeconds","slowmodeNextSendDate","migratedFromChatId","migratedFromMaxId","canViewParticipants","canViewStats","linkedChatId","hiddenPrehistory","availableReactions","defaultSendAs","statsDc","inviteLink","members","fetchMembers","kickedMembers","bannedUsers","adminMembers","adminUsers","mtpLinkedChat","slowMode","nextSendDate","migratedFrom","maxMessageId","canViewMembers","canViewStatistics","isPreHistoryHidden","enabledReactions","sendAsId","statisticsDcId","getFullChannelInfo","getFullChatInfo","fetchChatSettings","searchChats","query","q","localPeerIds","myResults","allChats","allUsers","localChats","r","localUsers","u","globalChats","globalUsers","fetchChat","requestChatUpdate","lastLocalMessage","noLastMessage","peers","lastRemoteMessage","saveDraft","clearDraft","updateChatMutedState","createChannel","noErrorUpdate","broadcast","newChannel","joinChannel","deleteChatUser","deleteChat","leaveChannel","deleteChannel","createGroupChat","newChat","editChatPhoto","uploadedPhoto","inputEntity","toggleChatPinned","shouldBePinned","toggleChatArchived","fetchChatFolders","byId","fetchRecommendedChatFolders","editChatFolder","folderUpdate","contacts","nonContacts","groups","bots","excludeArchived","excludeMuted","excludeRead","buildFilterFromApiFolder","deleteChatFolder","isActionSuccessful","recommendedChatFolders","folders","toggleDialogUnread","getChatByPhoneNumber","processResolvedPeer","getChatByUsername","togglePreHistoryHidden","isEnabled","enabled","updateChatDefaultBannedRights","updateChatMemberBannedRights","updateChatAdmin","updateChatTitle","updateChatAbout","toggleSignatures","memberFilter","fetchGroupsForDiscussion","setDiscussionGroup","group","migrateChat","openChatByInvite","isChannel","addChatMembers","all","deleteChatMember","viewMessages","sendMessages","sendMedia","sendStickers","sendGifs","sendGames","sendInline","embedLinks","sendPolls","changeInfo","inviteUsers","pinMessages","store","importChatInvite","setChatEnabledReactions","toggleIsProtected","File","constructor","fileBits","super","this","fetchMessages","pagination","RequestClass","c","threadInfos","fetchMessage","queue","sendMessage","replyingTo","gif","scheduledAt","noWebPage","sendAs","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","fetchBlob","lastModified","blobToFile","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","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","importContact","imported","updateContact","shouldSharePhoneNumber","addPhonePrivacyException","deleteContact","fetchProfilePhotos","userOrChat","fetchStickerSets","allStickers","sets","fetchRecentStickers","stickers","processStickerResult","fetchFavoriteStickers","fetchFeaturedStickers","faveSticker","unfave","fetchStickers","stickerSetShortName","packs","documentId","fetchAnimatedEmojis","fetchAnimatedEmojiEffects","searchStickers","fetchSavedGifs","gifs","processGifResult","saveGif","shouldUnsave","unsave","installStickerSet","uninstallStickerSet","searchGifs","config","resolvedPeer","gifSearchUsername","foundGif","fetchStickersForEmoji","fetchEmojiKeywords","fromVersion","langCode","keywords","emojiKeyword","keyword","emoticons","checkChatUsername","setChatUsername","updatePrivateLink","fetchExportedChatInvites","admin","exportedInvites","invites","editExportedChatInvite","replaceInvite","oldInvite","newInvite","exportChatInvite","deleteExportedChatInvite","deleteRevokedExportedChatInvites","fetchChatInviteImporters","offsetUser","isRequested","importers","importer","buildChatInviteImporter","hideChatJoinRequest","isApproved","approved","hideAllChatJoinRequests","hideChatReportPanel","EMAIL_UNCONFIRMED","EMAIL_HASH_EXPIRED","NEW_SALT_INVALID","NEW_SETTINGS_INVALID","CODE_INVALID","emailCodeController","getPasswordInfo","hasPassword","onRequestEmailCode","checkPassword","currentPassword","isCheckPassword","onError","clearPassword","updatePassword","email","newPassword","emailCodeCallback","onEmailCodeError","updateRecoveryEmail","provideRecoveryEmailCode","getGroupCall","discardGroupCall","editGroupCallParticipant","presentationPaused","videoStopped","videoPaused","raiseHand","editGroupCallTitle","exportGroupCallInvite","fetchGroupCallParticipants","leaveGroupCall","joinGroupCall","inviteHash","joinAs","createGroupCall","toJSNumber","joinGroupCallPresentation","toggleGroupCallStartSubscription","subscribed","leaveGroupCallPresentation","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","publicToken","public_token","buildPaymentForm","getReceipt","receipt","shipping","credentialsTitle","shippingPrices","shippingMethod","buildReceipt","buildEmojiSounds","appConfig","emojies_sounds","access_hash","atob","file_reference_base64","BETA_LANG_CODES","updateProfile","checkUsername","updateUsername","updateProfilePhoto","uploadProfilePhoto","fetchWallpapers","filteredWallpapers","wallpapers","pattern","uploadWallpaper","fetchBlockedContacts","blockedIds","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","fetchAppConfig","emojiSounds","defaultReaction","reactions_default","seenByMaxChatMembers","chat_read_mark_size_threshold","seenByExpiresAt","chat_read_mark_expire_period","buildApiConfig","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","sendWatchingEmojiInteraction","sendEmojiInteraction","v","getAvailableReactions","sendReaction","fetchMessageReactions","fetchMessageReactionsList","setDefaultReaction","buildGraph","isPercentage","x","y","columns","hasSecondYAxis","y_scaled","types","y0","zoomToken","labelFormatter","xTickFormatter","tooltipFormatter","xTooltipFormatter","labels","hideCaption","subchart","show","isStacked","stacked","datasets","item","names","color","colors","substring","indexOf","calculateMinimapRange","defaultZoom","range","minIndex","maxIndex","minimapRange","begin","labelFromIndex","labelToIndex","buildStatisticsOverview","previous","change","percentage","toFixed","fetchChannelStatistics","stats","growthGraph","followersGraph","muteGraph","topHoursGraph","languagesGraph","viewsBySourceGraph","newFollowersBySourceGraph","interactionsGraph","followers","viewsPerPost","sharesPerPost","enabledNotifications","part","total","recentTopMessages","recentMessageInteractions","fetchGroupStatistics","membersGraph","messagesGraph","actionsGraph","viewers","posters","fetchStatisticsAsyncGraph","initApi","_onUpdate","initialArgs","initUpdater","handleUpdate","initAuth","initChats","initMessages","initUsers","initStickers","initManagement","initTwoFaSettings","initCalls","initPayments","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","interval","isPending","shouldRunFirst","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","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","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","ConnectionTCPObfuscated","MTProtoSender","UpdateConnectionState","authFlow","checkAuthorization","downloadFile","WEBDOCUMENT_REQUEST_PART_SIZE","sizeTypes","apiId","apiHash","opts","DEFAULT_OPTIONS","_useIPV6","useIPV6","baseLogger","_log","floodSleepLimit","_eventBuilders","_phoneCodeHash","parseInt","_requestRetries","requestRetries","_connectionRetries","connectionRetries","_retryDelay","retryDelay","proxy","_proxy","_timeout","timeout","_autoReconnect","autoReconnect","_connection","_floodWaitedRequests","_initWith","InvokeWithLayer","layer","InitConnection","release","systemLangCode","_config","phoneCodeHashes","_exportedSenderPromises","_exportedSenderReleaseTimeouts","_additionalDcsDisabled","_loopStarted","_isSwitchingDc","_destroyed","_initSession","_sender","logger","retries","delay","connectTimeout","authKeyCallback","_authKeyCallback","bind","updateCallback","_handleUpdate","isMainSender","userDisconnected","_user_connected","isReconnecting","_disconnected","serverAddress","connect","setAuthKey","authKey","send","GetConfig","_updateLoop","load","setDC","lastPongAt","ping","PingDelayDisconnect","pingId","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","disconnectDelay","pingAt","lastInterval","attempts","wakeUpWarningTimeout","disconnected","clearTimeout","connected","getTime","_lastRequest","GetState","sender","newDc","DC","setKey","dc","_authenticated","auth","ExportAuthorization","req","ImportAuthorization","shouldReconnect","existingSender","_connectSender","_createExportedSender","isConnecting","_borrowExportedSender","onConnectionBreak","_cleanupExportedSender","getSender","inputLocation","messageOrMedia","Message","MessageMediaWebPage","WebPage","MessageMediaPhoto","Photo","_downloadPhoto","MessageMediaDocument","Document","_downloadDocument","MessageMediaContact","_downloadContact","WebDocument","WebDocumentNoProxy","_downloadWebDocument","isBig","loc","chatPhoto","UserProfilePhoto","ChatPhoto","InputPeerPhotoFileLocation","thumbVersion","InputStickerSetThumb","InputStickerSetID","thumbDcId","_pickFileSize","_downloadCachedPhotoSize","PhotoStrippedSize","PhotoSizeEmpty","PhotoCachedSize","InputPhotoFileLocation","thumbSize","doc","InputDocumentFileLocation","buff","downloaded","upload","GetWebFile","InputWebFileLocation","InputWebFileGeoPointLocation","geoPoint","InputGeoPoint","FloodWaitError","attempt","sendWithInvokeSupport","ServerError","FloodTestPhoneWaitError","PhoneMigrateError","NetworkMigrateError","UserMigrateError","_switchDC","MsgWaitError","isReady","GetUsers","InputUserSelf","authParams","apiCredentials","fileParams","event","Updates","UpdatesCombined","_processUpdate","UpdateShort","others","_dispatchUpdate","ptsDate","builder","race","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","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","to","ReadCancelledError","TypeNotFoundError","invalidConstructorId","remaining","alert","InvalidChecksumError","checksum","validChecksum","InvalidBufferError","payload","readInt32LE","SecurityError","BadMessageError","errorMessage","ErrorMessages","CdnFileTamperedError","RPCError","_fmtRequest","InvalidDCError","BadRequestError","UnauthorizedError","ForbiddenError","NotFoundError","AuthKeyError","FloodError","TimedOutError","capture","SlowModeWaitError","FileMigrateError","EmailUnconfirmedError","rpcErrorRe","Common","RPCBaseErrors","RPCErrorList","RPCMessageToError","rpcError","msgRegex","Cls","EventBuilder","func","blacklistChats","resolved","NewMessage","Raw","StopPropagation","_queue","canGet","resolveGet","canPush","resolvePush","returned","pop","coreObjects","tlobjects","stream","_last","readByte","readInt","readUInt32LE","readLargeInt","readFloat","readFloatLE","readDouble","readDoubleLE","getBuffer","tgReadBytes","firstByte","tgReadString","tgReadBool","tgReadDate","tgReadObject","constructorId","clazz","seek","tellPosition","setPosition","fromReader","tgReadVector","close","position","_stream","write","getValue","_level","level","isBrowser","browser","__nwjs","debug","messageFormat","canSend","levels","stack","format","toISOString","toUpperCase","log","MessageContainer","TLMessage","BinaryWriter","USE_INVOKE_AFTER_WITH","_state","_pendingStates","_ready","setReady","append","after","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","UpdateServerTimeOffset","BadServerSalt","BadMsgNotification","MsgDetailedInfo","MsgNewDetailedInfo","NewSessionCreated","FutureSalts","MsgsStateReq","MsgResendReq","MsgsAllInfo","LogOut","_dcId","_retries","_delay","_connectTimeout","_updateCallback","_autoReconnectCallback","autoReconnectCallback","_isMainSender","_onConnectionBreak","_send_loop_handle","_recv_loop_handle","_send_queue","_pending_state","_pending_ack","_last_acks","_handlers","_handleRPCResult","_handleContainer","_handleGzipPacked","_handlePong","_handleBadServerSalt","_handleBadNotification","_handleDetailedInfo","_handleNewDetailedInfo","_handleNewSessionCreated","_handleAck","_handleFutureSalts","_handleStateForgotten","_handleMsgAll","force","_connect","_disconnect","plain","_sendLoop","_recvLoop","ack","msgIds","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","origin","StorageSession","CACHE_NAME","_storageKey","cached","_sessionData","_callback","_authKeys","mainDcId","hashes","skipOnUpdate","_serverAddress","idb","_delete","del","_fetchFromCache","_saveToCache","localStorage","removeItem","getItem","setItem","_takeoutId","_updateStates","_authKey","sessionInfo","_sessionString","_loadFromSessionString","skipUpdateStorage","_updateStorage","asHex","mainDcIdStr","mainDcKey","StringSession","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","inflate","gzipped","toBytes","gzip","ungzip","containerLength","before","tlMessage","RpcError","innerCode","snakeToCamelCase","_","variableSnakeToCamelCase","CORE_TYPES","AUTH_KEY_TYPES","findAll","regex","matches","RegExp","exec","fromLine","line","argsMatch","currentConfig","hexId","representation","brace","argType","buildArgConfig","flagMatch","vectorMatch","ignoreIds","o","objAll","objByName","objByType","commentIndex","trim","followingTypes","dt","fill","__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 b08cd9bc..2272996f 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.687698a9e9aa68d75d14.js b/dist/main.040a86fe9347e4854db9.js similarity index 99% rename from dist/main.687698a9e9aa68d75d14.js rename to dist/main.040a86fe9347e4854db9.js index acdc6d6c..56090ab6 100644 --- a/dist/main.687698a9e9aa68d75d14.js +++ b/dist/main.040a86fe9347e4854db9.js @@ -1,2 +1,2 @@ -(()=>{"use strict";var e,t,n,r,o,d,a={1226:(e,t,n)=>{n.d(t,{t9:()=>c,u3:()=>l,g8:()=>s});var r=n(3716),o=n(6926),d=n(9118);let a;const u=new Map,i=new Map;function s(e,t){return a||(r.eM&&console.log(">>> START LOAD WORKER"),a=new Worker(new URL(n.p+n.u(742),n.b)),function(e){a.addEventListener("message",(t=>{let{data:n}=t;if("update"===n.type)e(n.update);else if("methodResponse"===n.type){const e=u.get(n.messageId);e&&(n.error?e.reject(n.error):e.resolve(n.response))}else if("methodCallback"===n.type){var r,o;null===(r=u.get(n.messageId))||void 0===r||null===(o=r.callback)||void 0===o||o.call(r,...n.callbackArgs)}else if("unhandledError"===n.type){var d;throw new Error(null===(d=n.error)||void 0===d?void 0:d.message)}}))}(e),"iOS"===t.platform&&window.addEventListener("focus",(()=>{m(),setTimeout((()=>m()),1e3)}))),f({type:"initApi",args:[t]})}function c(e){if(!a)return void(r.eM&&console.warn("API is not initialized"));for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o{try{await d}catch(e){}})(),d}function l(e){e.isCanceled=!0;const{messageId:t}=i.get(e)||{};t&&a.postMessage({type:"cancelProgress",messageId:t})}function f(e){const t=(0,o.Z)(u),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,i.set(e,r)}return u.set(t,r),d.catch((()=>{})).finally((()=>{u.delete(t),r.callback&&i.delete(r.callback)})),a.postMessage(n),d}const h=Date.now();async function m(){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()}}},6137:(e,t,n)=>{n.d(t,{IU:()=>o.I,Vv:()=>r.Vv,_Q:()=>r._Q,_f:()=>r._f});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,_Q:()=>d,_f:()=>o}),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.Spoiler="MessageEntitySpoiler",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(3555);const d=36,a=2147483647;function u(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 i(e,t){const n=[],r=[],o=e.length;let i,s,c,l,f,h,m,p,g,v,y,b,I;for(i=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(y=(w=e.charCodeAt(m++))-48<10?w-22:w-65<26?w-65:w-97<26?w-97:d,y>=d)throw RangeError("punycode_bad_input(2)");if(y>Math.floor((a-c)/g))throw RangeError("punycode_overflow(1)");if(c+=y*g,b=v<=l?1:v>=l+26?26:v-l,yMath.floor(a/(d-b)))throw RangeError("punycode_overflow(2)");g*=d-b}if(s=n.length+1,l=u(c-p,s,0===p),Math.floor(c/s)>a-i)throw RangeError("punycode_overflow(3)");i+=Math.floor(c/s),c%=s,t&&r.splice(c,0,e.charCodeAt(m-1)-65<26),n.splice(c,0,i),c++}var w;if(t)for(c=0,I=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 s=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{let{url:t,text:n,className:d,children:a,isRtl:u}=e;const{toggleSafeLinkModal:i,openTelegramLink:h}=(0,o.Sv)(),m=a||n,p=t!==m,g=(0,r.I4)((e=>e.ctrlKey||e.altKey||e.shiftKey||e.metaKey||!t||!t.match(s.FS)&&!t.match(s.g$)?!p||(i({url:t}),e.preventDefault(),!1):(e.preventDefault(),h({url:t}),!1)),[p,h,i,t]);if(!t)return;const v=(0,c.Z)(d||"text-entity-link",n.length>50&&"long-word-break-all");return r.ZP.createElement("a",{href:(0,l.X)(t),title:f(t),target:"_blank",rel:"noopener noreferrer",className:v,onClick:g,dir:u?"rtl":"auto"},m)}))},5376:(e,t,n)=>{n.d(t,{K2:()=>o,Oh:()=>a,mD:()=>d,v6:()=>u,yW:()=>r});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 a(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 u(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:()=>y});var r=n(4050),o=n(5806),d=n(8035),a=n(9937),u=n(996),i=n(2340),s=n(6752),c=n(8033),l=n(3555);const f=e=>{let{className:t,sender:n,children:o}=e;const{openChat:d}=(0,l.Sv)(),a=(0,r.I4)((()=>{n&&d({id:n.id})}),[n,d]);return n?r.ZP.createElement(c.Z,{className:(0,s.Z)("UserLink",t),onClick:a},o):o},h=e=>{let{className:t,message:n,children:o}=e;const{focusMessage:d}=(0,l.Sv)(),a=(0,r.I4)((()=>{n&&d({chatId:n.chatId,messageId:n.id})}),[d,n]);return n?r.ZP.createElement(c.Z,{className:(0,s.Z)("MessageLink",t),onClick:a},o):o},m=e=>{let{className:t,chatId:n,children:o}=e;const{openChat:d}=(0,l.Sv)(),a=(0,r.I4)((()=>{n&&d({id:n})}),[n,d]);return n?r.ZP.createElement(c.Z,{className:(0,s.Z)("ChatLink",t),onClick:a},o):o},p=e=>{let{className:t,groupCall:n,children:o}=e;const{joinGroupCall:d}=(0,l.Sv)(),a=(0,r.I4)((()=>{n&&d({id:n.id,accessHash:n.accessHash})}),[n,d]);return n?r.ZP.createElement(c.Z,{className:(0,s.Z)("GroupCallLink",t),onClick:a},o):o},g=32,v=" ";function y(e,t,n,r,o,d,u){let i=arguments.length>7&&void 0!==arguments[7]?arguments[7]:{};if(!t.content.action)return[];const{text:s,translationValues:c,amount:l,currency:f,call:h}=t.content.action,m=[],p=i.asPlainText||i.asTextWithSpoilers,g="Chat.Service.Group.UpdatedPinnedMessage1"!==s||d?s:"Message.PinnedGenericMessage";let y,M=e(g,null!=c&&c.length?c:void 0);return M.includes("%payment_amount%")&&(y=P(M,"%payment_amount%",(0,a.x)(l,f,e.code)),M=y.pop(),m.push(...y)),y=P(M,"%action_origin%",n?C(n,p)||v:r?S(e,r,p)||v:"User"),M=y.pop(),m.push(...y),y=P(M,"%target_user%",o?o.map((e=>C(e,p))).filter(Boolean):"User"),M=y.pop(),m.push(...y),y=P(M,"%message%",d?I(e,d,i):"a message"),M=y.pop(),m.push(...y),y=P(M,"%product%",d?b(d):"a product"),M=y.pop(),m.push(...y),y=P(M,"%target_chat%",u?E(u,p):"another chat"),m.push(...y),i.asPlainText?m.join("").trim():h?w(h,m):m}function b(e){return e.content&&e.content.invoice?e.content.invoice.title:"a product"}function I(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{asPlainText:d,asTextWithSpoilers:a}=n;if(d)return(0,o.MK)(e,t,void 0,g);const i=(0,u.e)(e,t,void 0,void 0,g);return a?r.ZP.createElement("span",null,i):r.ZP.createElement(h,{className:"action-link",message:t},i)}function w(e,t){return r.ZP.createElement(p,{groupCall:e},t)}function C(e,t){const n=(0,d.Z)((0,o.Js)(e),g);return t?n:r.ZP.createElement(f,{className:"action-link",sender:e},e&&(0,i.Z)(n))}function S(e,t,n){const a=(0,d.Z)((0,o.U)(e,t),g);return n?a:r.ZP.createElement(m,{className:"action-link",chatId:t.id},t&&(0,i.Z)(a))}function E(e,t){const n="another chat";return t?n:r.ZP.createElement(m,{className:"action-link",chatId:e},n)}function P(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,{X:()=>i,e:()=>s});var r=n(6137),o=n(5806),d=n(2340),a=n(8974),u=n(8035);function i(e,t,n,r,d){const{text:i,entities:s}=e.content.text||{};if(!i){const t=(0,o.UD)(e);return t?[(0,u.Z)(t,d)]:void 0}return(0,a.H)((0,u.Z)(i,d),s,t,n,void 0,e.id,r)}function s(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],a=arguments.length>3?arguments[3]:void 0,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:o.lN;const{entities:c}=t.content.text||{},l=null==c?void 0:c.some((e=>e.type===r.Vv.Spoiler));if(!l){const r=(0,u.Z)((0,o.MK)(e,t,n),s);return a?(0,d.Z)(r,["emoji","highlight"],{highlight:a}):(0,d.Z)(r)}const f=!n&&(0,o.Eb)(t),h=f?`${f} `:"",m=i(t,a,void 0,!0,s),p=(0,o.Kk)(e,t,m);return[h,...Array.isArray(p)?p:[p]].filter(Boolean)}},2340:(e,t,n)=>{n.d(t,{Z:()=>m});var r=n(4050),o=n(3681),d=n(3716),a=n(7361),u=n(4284),i=n(6752),s=n(782),c=n(7373),l=n(88);const f=/^[\d\wа-яё]$/i,h=/(\*\*|__).+?\1/g;function m(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["emoji"],n=arguments.length>2?arguments[2]:void 0;return"string"!=typeof e?[e]:(0,s.oA)(t.reduce(((e,t)=>{switch(t){case"escape_html":return p(e);case"hq_emoji":return o.Z.lastIndex=0,g(e,"big","jsx");case"emoji":return o.Z.lastIndex=0,g(e,"small","jsx");case"emoji_html":return o.Z.lastIndex=0,g(e,"small","html");case"br":return v(e,"jsx");case"br_html":return v(e,"html");case"highlight":return y(e,n.highlight);case"links":return I(e);case"simple_markdown":return w(e,"jsx");case"simple_markdown_html":return w(e,"html")}return e}),[e]))}function p(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)),[])}function g(e,t,n){return a.op?e:e.reduce(((e,d)=>{if("string"!=typeof d)return e.push(d),e;const a=(d=(0,u.g6)(d)).split(o.Z),s=d.match(o.Z)||[];return e.push(a[0]),s.reduce(((e,d,s)=>{const c=(0,u.U_)((0,o.l)(d));if(!c)return e;const l=(0,i.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*s+2;return a[f]&&e.push(a[f]),e}),e)}),[])}function v(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 a=n.trimLeft(),u=n.length-a.length;return e.push(String.fromCharCode(160).repeat(u)+a),o!==d.length-1&&e.push("jsx"===t?r.ZP.createElement("br",null):"
"),e}),[]);return[...e,...o]}),[])}function y(e,t){return e.reduce(((e,n)=>{if("string"!=typeof n||!t)return e.push(n),e;const o=n.toLowerCase(),d=o.indexOf(t.toLowerCase()),a=o[d+t.length];if(d<0||a&&a.match(f))return e.push(n),e;const u=[];return u.push(n.substring(0,d)),u.push(r.ZP.createElement("span",{className:"matching-text-highlight"},n.substring(d,d+t.length))),u.push(n.substring(d+t.length)),[...e,...u]}),[])}const b=new RegExp(`${d.FM}|${d.uW}`,"ig");function I(e){return e.reduce(((e,t)=>{if("string"!=typeof t)return e.push(t),e;const n=t.match(b);if(!n||!n.length)return e.push(t),e;const o=[];let d=n.shift(),a=0;for(;d;){const e=t.indexOf(d,a);o.push(t.substring(a,e)),d.startsWith("@")?o.push(r.ZP.createElement(c.Z,{username:d},d)):(d.endsWith("?")&&(d=d.slice(0,d.length-1)),o.push(r.ZP.createElement(l.Z,{text:d,url:d}))),a=e+d.length,d=n.shift()}return o.push(t.substring(a)),[...e,...o]}),[])}function w(e,t){return e.reduce(((e,n)=>{if("string"!=typeof n)return e.push(n),e;const o=n.split(h),d=n.match(h)||[];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 a=2*d+2;return o[a]&&e.push(o[a]),e}),e)}),[])}},8974:(e,t,n)=>{n.d(t,{z:()=>v,H:()=>g});var r=n(4050),o=n(3555),d=n(6137),a=n(2340),u=n(4319),i=n(711),s=n(7373),c=n(88),l=n(6752),f=n(706);const h=new Map,m=(0,l.y)("Spoiler"),p=(0,r.X$)((e=>{let{children:t,messageId:n}=e;const o=(0,r.sO)(null),[d,a,u]=(0,f.Z)(),i=(0,r.I4)((e=>{var t;e.preventDefault(),e.stopPropagation(),null===(t=h.get(n))||void 0===t||t.forEach((e=>e.reveal()));const r=o.current.innerText.length,d=1e3*Math.round(r/23),a=Math.max(5e3,Math.min(d,6e4));setTimeout((()=>{var e;null===(e=h.get(n))||void 0===e||e.forEach((e=>e.conceal())),u()}),a)}),[u,n]);return(0,r.d4)((()=>{if(n)return h.has(n)?h.get(n).push({reveal:a,conceal:u}):h.set(n,[{reveal:a,conceal:u}]),()=>{h.delete(n)}}),[u,i,d,n,a]),r.ZP.createElement("span",{className:m("&",!d&&"concealed",!d&&Boolean(n)&&"animated"),onClick:n&&!d?i:void 0},r.ZP.createElement("span",{className:m("content"),ref:o},t))}));function g(e,t,n,o,u,i,l){if(!t||!t.length)return y(e,n,o,u,l);const f=[];let h=!1;const m=function(e){const t=new Set,n=[];return e.forEach(((r,o)=>{if(t.has(o))return;const d=b(r,o,e,t);d&&(d.organizedIndexes.forEach((e=>{t.add(e)})),n.push(d))})),n}(t);function g(t,f,m,v){const b=[],{entity:E,nestedEntities:P}=m,{offset:M,length:A,type:k}=E;let T=e.substring(t,M);const N=T.length;T&&(h&&T.length>0&&"\n"===T[0]&&(T=T.substr(1),h=!1),T&&b.push(...y(T,n,o,u,l)));const L=t+N,R=L+A;let x=e.substring(M,M+A);const B=[];if(h&&x.length>0&&"\n"===x[0]&&(x=x.substr(1),h=!1),k===d.Vv.Pre&&(h=!0),P.length){let e=L;P.forEach(((t,n)=>{const{renderResult:r,entityEndIndex:o}=g(e,R,t,n===P.length-1);B.push(...r),e=o}))}const F=u?function(e,t,n){const r="string"==typeof t&&t,o=n.length?n.join(""):(0,a.Z)(t,["escape_html","emoji_html","br_html"]).join("");if(!r)return o;switch(e.type){case d.Vv.Bold:return`${o}`;case d.Vv.Italic:return`${o}`;case d.Vv.Underline:return`${o}`;case d.Vv.Code:return`${o}`;case d.Vv.Pre:return`\`\`\`
${o}
\`\`\``;case d.Vv.Strike:return`${o}`;case d.Vv.MentionName:return`${o}`;case d.Vv.Url:case d.Vv.TextUrl:return`${o}`;case d.Vv.Spoiler:return`${o}
`;default:return o}}(E,x,B):function(e,t,n,o,a,u){const i="string"==typeof t&&t,l=n.length?n:t;function f(){return y(l,o,void 0,void 0,u)}if(!i)return f();if(u){const t=f();return e.type===d.Vv.Spoiler?r.ZP.createElement(p,null,t):t}switch(e.type){case d.Vv.Bold:return r.ZP.createElement("strong",null,f());case d.Vv.Blockquote:return r.ZP.createElement("blockquote",null,f());case d.Vv.BotCommand:return r.ZP.createElement("a",{onClick:w,className:"text-entity-link",dir:"auto"},f());case d.Vv.Hashtag:case d.Vv.Cashtag:return r.ZP.createElement("a",{onClick:C,className:"text-entity-link",dir:"auto"},f());case d.Vv.Code:return r.ZP.createElement("code",{className:"text-entity-code",onClick:S,role:"textbox",tabIndex:0},f());case d.Vv.Email:return r.ZP.createElement("a",{href:`mailto:${i}`,target:"_blank",rel:"noopener noreferrer",className:"text-entity-link",dir:"auto"},f());case d.Vv.Italic:return r.ZP.createElement("em",null,f());case d.Vv.MentionName:return r.ZP.createElement(s.Z,{userId:e.userId},f());case d.Vv.Mention:return r.ZP.createElement(s.Z,{username:i},f());case d.Vv.Phone:return r.ZP.createElement("a",{href:`tel:${i}`,className:"text-entity-link",dir:"auto"},f());case d.Vv.Pre:return r.ZP.createElement("pre",{className:"text-entity-pre"},f());case d.Vv.Strike:return r.ZP.createElement("del",null,f());case d.Vv.TextUrl:case d.Vv.Url:return r.ZP.createElement(c.Z,{url:I(i,e),text:i},f());case d.Vv.Underline:return r.ZP.createElement("ins",null,f());case d.Vv.Spoiler:return r.ZP.createElement(p,{messageId:a},f());default:return f()}}(E,x,B,n,i,l);if(Array.isArray(F)?b.push(...F):b.push(F),v&&R0&&"\n"===t[0]&&(t=t.substring(1)),t&&b.push(...y(t,n,o,u,l))}return{renderResult:b,entityEndIndex:R}}let v=0;return m.forEach(((t,n)=>{const{renderResult:r,entityEndIndex:o}=g(v,e.length,t,n===m.length-1);f.push(...r),v=o})),f}function v(e){const{text:t,entities:n}=e||{};if(!t)return"";const r=g(t,n,void 0,void 0,!0);return Array.isArray(r)?r.join(""):r}function y(e,t,n,r,o){if(Array.isArray(e)){const d=[];return e.forEach((e=>{d.push(...y(e,t,n,r,o))})),d}if(r)return(0,a.Z)(e,["escape_html","emoji_html","br_html"]);const d=[n?"hq_emoji":"emoji"];return o||d.push("br"),t?(0,a.Z)(e,d.concat("highlight"),{highlight:t}):(0,a.Z)(e,d)}function b(e,t,n,r){const{offset:o,length:d}=e,a=new Set([t]);if(r.has(t))return;const u=[];return n.filter(((e,n)=>n>t&&e.offset>=o&&e.offsetb(e,n.indexOf(e),n,r))).filter(Boolean).forEach((e=>{let t=!1;e.organizedIndexes.forEach((e=>{t||a.has(e)||(t=!0),a.add(e)})),t&&u.push(e)})),{entity:e,organizedIndexes:a,nestedEntities:u}}function I(e,t){const{type:n,url:r}=t;return n===d.Vv.TextUrl&&r?r:e}function w(e){(0,o.Sv)().sendBotCommand({command:e.currentTarget.innerText})}function C(e){(0,o.Sv)().setLocalTextSearchQuery({query:e.currentTarget.innerText}),(0,o.Sv)().searchTextMessagesLocal()}function S(e){(0,u.TE)(e.currentTarget.innerText),(0,o.Sv)().showNotification({message:(0,i.i0)("TextCopied")})}},386:(e,t,n)=>{n.d(t,{b:()=>a,q:()=>d});var r=n(3716),o=n(7361);function d(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];o.cj||!document.activeElement||document.activeElement.id!==r.R2||!t&&e.target!==e.currentTarget||e.preventDefault()}function a(e){d(e,!0)}},7373:(e,t,n)=>{n.d(t,{Z:()=>a});var r=n(4050),o=n(3555),d=n(1192);const a=(0,o.c$)(((e,t)=>{let{userId:n}=t;return{userOrChat:n?(0,d.dy)(e,n):void 0}}))((e=>{let{username:t,userOrChat:n,children:d}=e;const{openChat:a,openChatByUsername:u}=(0,o.Sv)();return r.ZP.createElement("a",{onClick:()=>{n?a({id:n.id}):t&&u({username:t.substring(1)})},className:"text-entity-link",dir:"auto"},d)}))},231:(e,t,n)=>{n.d(t,{Z:()=>u});var r=n(4050),o=n(6752),d=n(9204),a=n(8512);const u=e=>{let{ref:t,type:n="button",id:u,onClick:i,onContextMenu:s,onMouseDown:c,onMouseEnter:l,onMouseLeave:f,onFocus:h,children:m,size:p="default",color:g="primary",backgroundImage:v,className:y,round:b,pill:I,fluid:w,isText:C,isLoading:S,ariaLabel:E,ariaControls:P,hasPopup:M,href:A,download:k,disabled:T,ripple:N,faded:L,tabIndex:R,isRtl:x,withClickPropagation:B}=e,F=(0,r.sO)(null);t&&(F=t);const[O,D]=(0,r.eJ)(!1),Z=(0,o.Z)("Button",y,p,g,b&&"round",I&&"pill",w&&"fluid",T&&"disabled",C&&"text",S&&"loading",N&&"has-ripple",L&&"faded",O&&"clicked",v&&"with-image"),_=(0,r.I4)((e=>{!T&&i&&i(e),D(!0),setTimeout((()=>{D(!1)}),400)}),[T,i]),$=(0,r.I4)((e=>{B||e.preventDefault(),!T&&c&&c(e)}),[c,T,B]);return A?r.ZP.createElement("a",{ref:F,id:u,className:Z,href:A,title:E,download:k,tabIndex:R,dir:x?"rtl":void 0,"aria-label":E,"aria-controls":P},m,!T&&N&&r.ZP.createElement(a.Z,null)):r.ZP.createElement("button",{ref:F,id:u,type:n,className:Z,onClick:_,onContextMenu:s,onMouseDown:$,onMouseEnter:l&&!T?l:void 0,onMouseLeave:f&&!T?f:void 0,onFocus:h&&!T?h:void 0,"aria-label":E,"aria-controls":P,"aria-haspopup":M,title:E,tabIndex:R,dir:x?"rtl":void 0,style:v?`background-image: url(${v})`:void 0},S?r.ZP.createElement("div",null,r.ZP.createElement("span",{dir:x?"auto":void 0},"Please wait..."),r.ZP.createElement(d.Z,{color:C?"blue":"white"})):m,!T&&N&&r.ZP.createElement(a.Z,null))}},4605:(e,t,n)=>{n.d(t,{Z:()=>i});var r=n(4050),o=n(6752),d=n(9107),a=n(2340),u=n(9204);const i=(0,r.X$)((e=>{let{id:t,name:n,value:i,label:s,subLabel:c,checked:l,tabIndex:f,disabled:h,round:m,blocking:p,isLoading:g,onChange:v,onCheck:y}=e;const b=(0,d.Z)(),I=(0,r.I4)((e=>{v&&v(e),y&&y(e.currentTarget.checked)}),[v,y]),w=(0,o.Z)("Checkbox",h&&"disabled",m&&"round",g&&"loading",p&&"blocking");return r.ZP.createElement("label",{className:w,dir:b.isRtl?"rtl":void 0},r.ZP.createElement("input",{type:"checkbox",id:t,name:n,value:i,checked:l,disabled:h,tabIndex:f,onChange:I}),r.ZP.createElement("div",{className:"Checkbox-main"},r.ZP.createElement("span",{className:"label",dir:"auto"},(0,a.Z)(s)),c&&r.ZP.createElement("span",{className:"subLabel",dir:"auto"},(0,a.Z)(c))),g&&r.ZP.createElement(u.Z,null))}))},3106:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(2328);const d=e=>{let{trigger:t,className:n,children:d,positionX:a="left",positionY:u="top",footer:i,forceOpen:s,onOpen:c,onClose:l}=e;const f=(0,r.sO)(null),h=(0,r.sO)(null),[m,p]=(0,r.eJ)(!1);return r.ZP.createElement("div",{ref:h,className:`DropdownMenu ${n||""}`,onKeyDown:e=>{const t=f.current;if(!m||40!==e.keyCode||!t)return;const n=document.activeElement,r=Array.from(t.children);n&&-1!==r.indexOf(n)||r[0].focus()}},t({onTrigger:()=>{p(!m),m?l&&l():c&&c()},isOpen:m}),r.ZP.createElement(o.Z,{ref:f,containerRef:h,isOpen:m||Boolean(s),className:n||"",positionX:a,positionY:u,footer:i,autoClose:!0,onClose:()=>{p(!1),l&&l()},shouldSkipTransition:s},d))}},7687:(e,t,n)=>{n.d(t,{Z:()=>a});var r=n(4050),o=n(6752),d=n(9107);const a=(0,r.X$)((e=>{let{ref:t,id:n,className:a,value:u,label:i,error:s,success:c,disabled:l,readOnly:f,placeholder:h,autoComplete:m,inputMode:p,maxLength:g,tabIndex:v,onChange:y,onInput:b,onKeyPress:I,onKeyDown:w,onBlur:C,onPaste:S}=e;const E=(0,d.Z)(),P=s||c||i,M=(0,o.Z)("input-group",u&&"touched",s?"error":c&&"success",l&&"disabled",f&&"disabled",P&&"with-label",a);return r.ZP.createElement("div",{className:M,dir:E.isRtl?"rtl":void 0},r.ZP.createElement("input",{ref:t,className:"form-control",type:"text",id:n,dir:"auto",value:u||"",tabIndex:v,placeholder:h,maxLength:g,autoComplete:m,inputMode:p,disabled:l,readOnly:f,onChange:y,onInput:b,onKeyPress:I,onKeyDown:w,onBlur:C,onPaste:S,"aria-label":P}),P&&r.ZP.createElement("label",{htmlFor:n},P))}))},8033:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(6752);const d=e=>{let{children:t,className:n,isRtl:d,onClick:a}=e;const u=(0,r.I4)((e=>{e.preventDefault(),a(e)}),[a]);return r.ZP.createElement("a",{href:"#",className:(0,o.Z)("Link",n),dir:d?"rtl":"auto",onClick:a?u:void 0},t)}},4288:(e,t,n)=>{n.d(t,{Z:()=>a});var r=n(4050),o=n(9204),d=n(6752);const a=(0,r.X$)((e=>{let{color:t="blue",backgroundColor:n,onClick:a}=e;return r.ZP.createElement("div",{className:(0,d.Z)("Loading",a&&"interactive"),onClick:a},r.ZP.createElement(o.Z,{color:t,backgroundColor:n}))}))},2328:(e,t,n)=>{n.d(t,{Z:()=>m});var r=n(4050),o=n(1212),d=n(2313),a=n(8758),u=n(274),i=n(3989),s=n(6752),c=n(8674),l=n(6590),f=n(386),h=n(7361);const m=e=>{let{ref:t,containerRef:n,isOpen:m,id:p,className:g,style:v,bubbleStyle:y,ariaLabelledBy:b,children:I,transformOriginX:w,transformOriginY:C,positionX:S="left",positionY:E="top",autoClose:P=!1,footer:M,noCloseOnBackdrop:A=!1,noCompact:k,onCloseAnimationEnd:T,onClose:N,onMouseEnter:L,onMouseLeave:R,shouldSkipTransition:x}=e,B=(0,r.sO)(null);t&&(B=t);const F=n||B,{transitionClassNames:O}=(0,o.Z)(m,T,x,void 0,x);(0,r.d4)((()=>m&&N?(0,i.Z)(N):void 0),[m,N]),(0,l.ZP)(m,N,void 0,void 0,P),(0,u.Z)((e=>{let[t]=e;(m||!m&&!0===t)&&(0,c.YW)(200)}),[m]);const D=(0,d.Z)(B,m,P?N:void 0,void 0,!0);(0,a.Z)(m,F,A?void 0:N);const Z=(0,s.Z)("bubble menu-container custom-scroll",E,S,M&&"with-footer",O),_=void 0!==C?`${C}px`:void 0,$=void 0!==w?`${w}px`:void 0;return r.ZP.createElement("div",{id:p,className:(0,s.Z)("Menu no-selection",!k&&h.FW&&"compact",!h.gk&&"no-blur",g),style:v,"aria-labelledby":b,role:b?"menu":void 0,onKeyDown:m?D:void 0,onMouseEnter:L,onMouseLeave:m?R:void 0},m&&r.ZP.createElement("div",{className:"backdrop",onMouseDown:f.b}),r.ZP.createElement("div",{ref:B,className:Z,style:`transform-origin: ${$||S} ${_||E};${y||""}`,onClick:P?N:void 0},I,M&&r.ZP.createElement("div",{className:"footer"},M)))}},8964:(e,t,n)=>{n.d(t,{Z:()=>u});var r=n(4050),o=n(6752),d=n(9107),a=n(7361);const u=e=>{const{icon:t,className:n,children:u,onClick:i,href:s,download:c,disabled:l,destructive:f,ariaLabel:h}=e,m=(0,d.Z)(),p=(0,r.I4)((e=>{if(l||!i)return e.stopPropagation(),void e.preventDefault();i(e)}),[l,i]),g=(0,r.I4)((e=>{if(13===e.keyCode||32===e.keyCode)return l||!i?(e.stopPropagation(),void e.preventDefault()):void i(e)}),[l,i]),v=(0,o.Z)("MenuItem",n,l&&"disabled",f&&"destructive",a.FW&&"compact"),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:v,href:s,download:c,"aria-label":h,title:h,target:s.startsWith(window.location.origin)?"_self":"_blank",rel:"noopener noreferrer",dir:m.isRtl?"rtl":void 0,onClick:i},y):r.ZP.createElement("div",{role:"button",tabIndex:0,className:v,onClick:p,onKeyDown:g,"aria-label":h,title:h,dir:m.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(),a=o.offsetWidth/2;t([...e,{x:r.clientX-d.x-a/2,y:r.clientY-d.y-a/2,size:a}]),requestAnimationFrame((()=>{n()}))}),[e,n]);return r.ZP.createElement("div",{className:"ripple-container",onMouseDown:d},e.map((e=>{let{x:t,y:n,size:o}=e;return r.ZP.createElement("span",{style:`left: ${t}px; top: ${n}px; width: ${o}px; height: ${o}px;`})})))}))},9204:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(6752);const d=e=>{let{color:t="blue",backgroundColor:n}=e;return r.ZP.createElement("div",{className:(0,o.Z)("Spinner",t,n&&"with-background",`bg-${n}`)},r.ZP.createElement("div",null))}},3716:(e,t,n)=>{n.d(t,{$E:()=>ke,$O:()=>qe,AE:()=>ae,AJ:()=>ue,AR:()=>z,Bg:()=>Ye,CX:()=>W,Cg:()=>u,Cy:()=>b,DC:()=>be,DU:()=>He,Db:()=>Xe,EG:()=>ze,EN:()=>x,FD:()=>Ue,FM:()=>De,FS:()=>$e,FV:()=>Ve,Hk:()=>F,It:()=>nt,Ji:()=>o,K2:()=>Ce,K7:()=>he,LH:()=>ut,Mw:()=>ye,Nf:()=>We,Ng:()=>Re,Ov:()=>R,PM:()=>Me,Q:()=>ve,QU:()=>X,Qx:()=>$,R2:()=>q,Rk:()=>y,Ro:()=>dt,S:()=>i,SG:()=>w,Ti:()=>s,Uh:()=>p,V$:()=>se,VC:()=>Oe,Vk:()=>O,Vv:()=>rt,Vx:()=>h,WS:()=>Ge,Y:()=>Le,Y7:()=>Ie,YQ:()=>T,ZT:()=>a,_m:()=>te,aC:()=>at,aw:()=>je,b6:()=>H,bK:()=>ce,bM:()=>Se,b_:()=>f,by:()=>P,ck:()=>le,dI:()=>Fe,eA:()=>l,eM:()=>d,ee:()=>E,fK:()=>ie,fo:()=>S,g:()=>ot,g$:()=>_e,gJ:()=>v,hT:()=>k,iC:()=>r,jT:()=>ee,jV:()=>Ae,kU:()=>Ne,ks:()=>ne,ku:()=>Ee,l3:()=>re,lF:()=>C,lO:()=>g,lW:()=>I,lo:()=>A,mU:()=>et,mo:()=>D,mw:()=>U,nY:()=>Y,oB:()=>j,oG:()=>xe,o_:()=>J,ou:()=>c,p3:()=>tt,pR:()=>Te,pn:()=>B,qU:()=>Z,qp:()=>ge,rO:()=>de,rS:()=>N,r_:()=>K,s2:()=>Q,sR:()=>Je,sd:()=>m,t4:()=>Ke,t_:()=>L,uW:()=>Ze,u_:()=>oe,ul:()=>_,vi:()=>Qe,w7:()=>me,wG:()=>Be,xS:()=>G,xn:()=>fe,yK:()=>we,z7:()=>pe,zq:()=>Pe,zy:()=>V});const r="Telegram WebZ",o="1.38.1",d=!1,a=!1,u=!1,i="Shoot!\nSomething went wrong, please see the error details in Dev Tools Console.",s="Telegram",c=" [Inactive]",l=!1,f="user_auth",h="GramJs:sessionId",m=!1,p="tt-global-state",g=500,v=200,y=30,b=!1,I="tt-media",w="tt-media-avatars",C="tt-media-progressive",S="tt-custom-bg",E="tt-lang-packs-v8",P=[1,5,10,50,100,500],M="undefined"!=typeof window&&window.innerHeight>=900,A=1,k=M?60:40,T=2*k,N=72,L=M?30:25,R=100,x=42,B=42,F=20,O=30,D=200,Z=500,_=20,$=1,U=1,j=0,V=2,W=V,G=16,H=17,z=15,K=1e4,J=3e3,q="editable-message-text",Y="editable-message-text-modal",Q="data-has-custom-appendix",X=1440,ee=1150,te=1275,ne=925,re=600,oe=950,de=450,ae=1e9,ue="0",ie=100,se=1500,ce=250,le=600,fe=500,he=(Math.round((ce+le)/2),new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),13),me=11,pe=160,ge=120,ve=64,ye=48,be=32,Ie=64,we=64,Ce=160,Se=140,Ee=100,Pe=100,Me=140,Ae=140,ke="NO_STICKER_SET",Te="en",Ne=200,Le=450,Re="video/quicktime",xe=new Set(["image/png","image/gif","image/jpeg"]),Be=new Set(["video/mp4"]),Fe=new Set([...xe,...Be]),Oe="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()@:%_+.~#?&/=]*)",Ze="(@[\\w\\d_-]+)",_e=/^tg:(\/\/)?([?=&\d\w_-]+)?/gm,$e=/^(?:https?:\/\/)?(?:t\.me\/)/gm,Ue=new Set(["AU","BD","CA","CO","EG","HN","IE","IN","JO","MX","MY","NI","NZ","PH","PK","SA","SV","US"]),je="777000",Ve="1271266957",We=0,Ge=1,He=10,ze=5,Ke=2147483646,Je="en",qe="android",Ye=["android","ios","tdesktop","macos"],Qe="TelegramTips",Xe=["ar","pt-br","id","it","ko","ms","pl","es","tr"],et="https://bugs.telegram.org/?tag_ids=41&sort=time",tt="#A2AF8E",nt="#0F0F0F",rt="#0a0a0a8c",ot="rgba(90, 110, 70, 0.6)",dt=100,at=100*dt,ut=!1},5456:(e,t,n)=>{var r=n(3555),o=n(1226),d=n(3716),a=n(7361),u=n(8406),i=n(9524),s=n(7358),c=n(3100),l=n(1622);(0,r.iw)("initApi",(async(e,t)=>{d.Cg||(await(0,c.Qw)(),(0,c.f3)()),(0,o.g8)(t.apiUpdate,{userAgent:navigator.userAgent,platform:a.Lt,sessionData:(0,c.K8)(),isTest:window.location.search.includes("test"),isMovSupported:a.pA,isWebmSupported:a.Hh})})),(0,r.iw)("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.iw)("setAuthCode",((e,t,n)=>{const{code:r}=n;return(0,o.t9)("provideAuthCode",r),{...e,authIsLoading:!0,authError:void 0}})),(0,r.iw)("setAuthPassword",((e,t,n)=>{const{password:r}=n;return(0,o.t9)("provideAuthPassword",r),{...e,authIsLoading:!0,authError:void 0}})),(0,r.iw)("uploadProfilePhoto",((e,t,n)=>{const{file:r}=n;(0,o.t9)("uploadProfilePhoto",r)})),(0,r.iw)("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.iw)("returnToAuthPhoneNumber",(e=>((0,o.t9)("restartAuth"),{...e,authError:void 0}))),(0,r.iw)("goToAuthQrCode",(e=>((0,o.t9)("restartAuthWithQr"),{...e,authIsLoadingQrCode:!0,authError:void 0}))),(0,r.iw)("saveSession",((e,t,n)=>{const{sessionData:r}=n;r?(0,c.wX)(n.sessionData,e.currentUserId):(0,c.jv)()})),(0,r.iw)("signOut",(async(e,t,n)=>{try{await(0,u.r1)(),await(0,o.t9)("destroy"),await(0,l.IT)(!1)}catch(e){}(0,r.Sv)().reset(),null!=n&&n.forceInitApi&&(0,r.Sv)().initApi()})),(0,r.iw)("reset",(()=>{(0,c.jv)(),i.clear(d.lW),i.clear(d.SG),i.clear(d.lF),i.clear(d.fo);const e=d.ee.replace(/\d+$/,""),t=(d.ee.match(/\d+$/)||[0])[0];for(let n=0;n{(0,o.t9)("disconnect")})),(0,r.iw)("loadNearestCountry",(async e=>{if("connectionStateReady"!==e.connectionState)return;const t=await(0,o.t9)("fetchNearestCountry");return{...(0,r.Rd)(),authNearestCountry:t}})),(0,r.iw)("setDeviceToken",((e,t,n)=>({...e,push:{deviceToken:n,subscribedAt:Date.now()}}))),(0,r.iw)("deleteDeviceToken",(e=>({...e,push:void 0})))},1371:(e,t,n)=>{var r=n(3555),o=n(1713),d=n(3716),a=n(1226),u=n(782),i=n(8406),s=n(711),c=n(1192),l=n(5406),f=n(5806);function h(e,t){let{visibility:n,allowedIds:r,deniedIds:o}=t;const{users:{byId:d},chats:{byId:a}}=e,u={visibility:n};let i,s;const c=e=>{if(!(0,f.YC)(e))return;const{id:t,accessHash:n}=d[e]||{};return t?{id:t,accessHash:n}:void 0},l=e=>{if((0,f.YC)(e))return;const t=a[e];return t?{id:t.id}:void 0};return"contacts"!==n&&"nobody"!==n||(i=r.map(c).filter(Boolean),s=r.map(l).filter(Boolean),i.length>0&&(u.allowedUsers=i),s.length>0&&(u.allowedChats=s)),"everybody"!==n&&"contacts"!==n||(i=o.map(c).filter(Boolean),s=o.map(l).filter(Boolean),i.length>0&&(u.blockedUsers=i),s.length>0&&(u.blockedChats=s)),u}(0,r.iw)("updateProfile",(async(e,t,n)=>{const{photo:d,firstName:u,lastName:i,bio:s,username:f}=n,{currentUserId:h}=e;if(h){if((0,r.R3)({...(0,r.Rd)(),profileEdit:{progress:o.rN.InProgress}}),d&&await(0,a.t9)("updateProfilePhoto",d),(u||i||s)&&await(0,a.t9)("updateProfile",{firstName:u,lastName:i,about:s})){e=(0,r.Rd)();const t=h&&(0,c.dy)(e,h);t&&(0,r.R3)((0,l.Nq)(e,t.id,{firstName:u,lastName:i,fullInfo:{...t.fullInfo,bio:s}}))}return f&&await(0,a.t9)("updateUsername",f)&&h&&(0,r.R3)((0,l.Nq)((0,r.Rd)(),h,{username:f})),{...(0,r.Rd)(),profileEdit:{progress:o.rN.Complete}}}})),(0,r.iw)("checkUsername",(async(e,t,n)=>{const{username:d}=n;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 u=await(0,a.t9)("checkUsername",d);return e=(0,r.Rd)(),{...e,profileEdit:{...e.profileEdit,isUsernameAvailable:u}}})),(0,r.iw)("loadWallpapers",(async()=>{const e=await(0,a.t9)("fetchWallpapers");if(!e)return;const t=(0,r.Rd)();return{...t,settings:{...t.settings,loadedWallpapers:e.wallpapers}}})),(0,r.iw)("uploadWallpaper",(async(e,t,n)=>{const d=n,u=URL.createObjectURL(d);(0,r.R3)({...e,settings:{...e.settings,loadedWallpapers:[{slug:o.mp,document:{fileName:"",size:d.size,mimeType:d.type,previewBlobUrl:u}},...e.settings.loadedWallpapers||[]]}});const i=await(0,a.t9)("uploadWallpaper",d);if(!i)return;const{wallpaper:s}=i;if(!(e=(0,r.Rd)()).settings.loadedWallpapers)return;const c=e.settings.loadedWallpapers[0];if(!c||c.slug!==o.mp)return;const l={...s,document:{...s.document,previewBlobUrl:u}};return{...e,settings:{...e.settings,loadedWallpapers:[l,...e.settings.loadedWallpapers.slice(1)]}}})),(0,r.iw)("loadBlockedContacts",(async e=>{var t,n;const o=await(0,a.t9)("fetchBlockedContacts");if(o)return e=(0,r.Rd)(),null!==(t=o.users)&&void 0!==t&&t.length&&(e=(0,l.Sh)(e,(0,u.ee)(o.users,"id"))),null!==(n=o.chats)&&void 0!==n&&n.length&&(e=(0,l.GL)(e,(0,u.ee)(o.chats,"id"))),{...e,blocked:{...e.blocked,ids:[...e.blocked.ids||[],...o.blockedIds],totalCount:o.totalCount}}})),(0,r.iw)("blockContact",(async(e,t,n)=>{const{contactId:o,accessHash:d}=n;if(await(0,a.t9)("blockContact",o,d))return(0,l.O4)((0,r.Rd)(),o)})),(0,r.iw)("unblockContact",(async(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}if(await(0,a.t9)("unblockContact",o,d))return(0,l.rB)((0,r.Rd)(),o)})),(0,r.iw)("loadAuthorizations",(async()=>{const e=await(0,a.t9)("fetchAuthorizations");if(e)return{...(0,r.Rd)(),activeSessions:e}})),(0,r.iw)("terminateAuthorization",(async(e,t,n)=>{const{hash:o}=n;if(await(0,a.t9)("terminateAuthorization",o))return e=(0,r.Rd)(),{...e,activeSessions:e.activeSessions.filter((e=>e.hash!==o))}})),(0,r.iw)("terminateAllAuthorizations",(async e=>{if(await(0,a.t9)("terminateAllAuthorizations"))return e=(0,r.Rd)(),{...e,activeSessions:e.activeSessions.filter((e=>e.isCurrent))}})),(0,r.iw)("loadNotificationExceptions",(async e=>{const{serverTimeOffset:t}=e,n=await(0,a.t9)("fetchNotificationExceptions",{serverTimeOffset:t});if(n)return(0,l.aJ)((0,r.Rd)(),n)})),(0,r.iw)("loadNotificationSettings",(async e=>{const{serverTimeOffset:t}=e,n=await(0,a.t9)("fetchNotificationSettings",{serverTimeOffset:t});if(n)return(0,l.BI)((0,r.Rd)(),n)})),(0,r.iw)("updateNotificationSettings",(async(e,t,n)=>{const{peerType:o,isSilent:d,shouldShowPreviews:u}=n;if(await(0,a.t9)("updateNotificationSettings",o,{isSilent:d,shouldShowPreviews:u}))return(0,l.HN)((0,r.Rd)(),o,d,u)})),(0,r.iw)("updateWebNotificationSettings",((e,t,n)=>{(0,r.R3)((0,l.BI)(e,n));const{hasPushNotifications:o,hasWebNotifications:d}=e.settings.byKey;d&&o?(0,i.Ld)():(0,i.r1)()})),(0,r.iw)("updateContactSignUpNotification",(async(e,t,n)=>{const{isSilent:o}=n;if(await(0,a.t9)("updateContactSignUpNotification",o))return(0,l.BI)((0,r.Rd)(),{hasContactJoinedNotifications:!o})})),(0,r.iw)("loadLanguages",(async()=>{const e=await(0,a.t9)("fetchLanguages");if(e)return(0,l.BI)((0,r.Rd)(),{languages:e})})),(0,r.iw)("loadPrivacySettings",(async e=>{const[t,n,o,d,u]=await Promise.all([(0,a.t9)("fetchPrivacySettings","phoneNumber"),(0,a.t9)("fetchPrivacySettings","lastSeen"),(0,a.t9)("fetchPrivacySettings","profilePhoto"),(0,a.t9)("fetchPrivacySettings","forwards"),(0,a.t9)("fetchPrivacySettings","chatInvite")]);if(t&&n&&o&&d&&u)return(e=(0,r.Rd)()).settings.privacy.phoneNumber=t,e.settings.privacy.lastSeen=n,e.settings.privacy.profilePhoto=o,e.settings.privacy.forwards=d,e.settings.privacy.chatInvite=u,e})),(0,r.iw)("setPrivacyVisibility",(async(e,t,n)=>{const{privacyKey:o,visibility:d}=n,{privacy:{[o]:u}}=e.settings;if(!u)return;const i=h(e,{visibility:d,allowedIds:[...u.allowUserIds,...u.allowChatIds],deniedIds:[...u.blockUserIds,...u.blockChatIds]}),s=await(0,a.t9)("setPrivacySettings",o,i);return s?(e=(0,r.Rd)(),{...e,settings:{...e.settings,privacy:{...e.settings.privacy,[o]:s}}}):void 0})),(0,r.iw)("setPrivacySettings",(async(e,t,n)=>{const{privacyKey:o,isAllowList:d,contactsIds:u}=n,{privacy:{[o]:i}}=e.settings;if(!i)return;const s=h(e,{visibility:i.visibility,allowedIds:d?u:[...i.allowUserIds,...i.allowChatIds],deniedIds:d?[...i.blockUserIds,...i.blockChatIds]:u}),c=await(0,a.t9)("setPrivacySettings",o,s);return c?(e=(0,r.Rd)(),{...e,settings:{...e.settings,privacy:{...e.settings.privacy,[o]:c}}}):void 0})),(0,r.iw)("updateIsOnline",((e,t,n)=>{(0,a.t9)("updateIsOnline",n)})),(0,r.iw)("loadContentSettings",(async()=>{const e=await(0,a.t9)("fetchContentSettings");if(e)return(0,l.BI)((0,r.Rd)(),e)})),(0,r.iw)("updateContentSettings",(async(e,t,n)=>{if((0,r.R3)((0,l.BI)((0,r.Rd)(),{isSensitiveEnabled:n})),!await(0,a.t9)("updateContentSettings",n))return(0,l.BI)((0,r.Rd)(),{isSensitiveEnabled:!n})})),(0,r.iw)("loadCountryList",(async function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{langCode:o}=n;o||(o=e.settings.byKey.language);const d=await(0,a.t9)("fetchCountryList",{langCode:o});if(d)return{...(0,r.Rd)(),countryList:d}})),(0,r.iw)("ensureTimeFormat",(async(e,t)=>{if(e.authNearestCountry){const n=d.FD.has(e.authNearestCountry.toUpperCase())?"12h":"24h";t.setSettingOption({timeFormat:n}),(0,s.qf)(n)}if(e.settings.byKey.wasTimeFormatSetManually)return;const n=await(0,a.t9)("fetchNearestCountry");if(n){const e=d.FD.has(n.toUpperCase())?"12h":"24h";t.setSettingOption({timeFormat:e}),(0,s.qf)(e)}})),(0,r.iw)("loadAppConfig",(async()=>{const e=await(0,a.t9)("fetchAppConfig");if(e)return{...(0,r.Rd)(),appConfig:e}}))},8304:(e,t,n)=>{var r=n(3555),o=n(3716),d=n(8406),a=n(5406),u=n(711),i=n(1192),s=n(1622),c=n(1947);(0,r.iw)("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,i.dZ)(e);t&&n&&(0,d.Ld)(),(0,u.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,s.IT)(!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,s.IT)(!0),(0,r.R3)({...t,isLoggingOut:!1})}}(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)();if(t!==n.connectionState&&((0,r.R3)({...n,connectionState:t}),"connectionStateBroken"===t)){const e=!n.authState||["authorizationStateWaitPhoneNumber","authorizationStateWaitCode","authorizationStateWaitPassword","authorizationStateWaitRegistration","authorizationStateWaitQrCode"].includes(n.authState);(0,r.Sv)().signOut({forceInitApi:e})}}(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.Sv)().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,a.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}}}))},9005:(e,t,n)=>{var r=n(3555),o=n(3716),d=n(7361),a=n(711),u=n(7370),i=n(1192),s=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,i.Pu)(n),{animationLevel:a}=n.settings.byKey;d!==t&&((0,u.Z)(d,a===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.iw)("init",(e=>{const{animationLevel:t,messageTextSize:n,language:r}=e.settings.byKey,l=(0,i.Pu)(e);(0,a.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,u.Z)(l,t===o.zy),(0,c.$)(),(0,s.px)(),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.iw)("setIsUiReady",((e,t,n)=>{const{uiReadyState:r}=n;return 2===r&&document.body.classList.remove("initial"),{...e,uiReadyState:r}})),(0,r.iw)("setAuthPhoneNumber",((e,t,n)=>{const{phoneNumber:r}=n;return{...e,authPhoneNumber:r}})),(0,r.iw)("setAuthRememberMe",((e,t,n)=>({...e,authRememberMe:Boolean(n)}))),(0,r.iw)("clearAuthError",(e=>({...e,authError:void 0}))),(0,r.iw)("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})}))},3456:(e,t,n)=>{var r=n(3555),o=n(5406);(0,r.iw)("setSettingOption",((e,t,n)=>(0,o.BI)(e,n))),(0,r.iw)("setThemeSettings",((e,t,n)=>{const{theme:r,...d}=n;return(0,o.lr)(e,r,d)}))},2825:(e,t,n)=>{n.d(t,{$l:()=>$,Bf:()=>h,G9:()=>m,GM:()=>C,H5:()=>N,Hd:()=>R,Hp:()=>P,Mg:()=>k,Nl:()=>M,Qm:()=>T,RT:()=>E,Ru:()=>v,SB:()=>D,Sm:()=>F,U:()=>w,VE:()=>A,YC:()=>f,ZV:()=>p,cc:()=>O,eA:()=>g,hu:()=>S,i4:()=>B,ih:()=>_,l6:()=>b,pE:()=>x,pK:()=>y,q8:()=>L,zF:()=>Z,zX:()=>I});var r=n(6137),o=n(3716),d=n(782),a=n(3311),u=n(790),i=n(5765);const s=Date.now()/1e3+31622400,c=3e9,l=3e8;function f(e){return"number"==typeof e?e>0:!e.startsWith("-")}function h(e){return m(e)||p(e)}function m(e){return"chatTypeBasicGroup"===e.type}function p(e){return"chatTypeSuperGroup"===e.type}function g(e){return"chatTypeChannel"===e.type}function v(e){return"chatTypePrivate"===e.type||"chatTypeBasicGroup"===e.type}function y(e){return e===o.FV}function b(e){switch(e.type){case"chatTypePrivate":return"PrivateChat";case"chatTypeBasicGroup":case"chatTypeSuperGroup":return"AccDescrGroup";case"chatTypeChannel":return"AccDescrChannel";default:return"Chat"}}function I(e){if("chatTypePrivate"===e.type||"chatTypeSecret"===e.type)return e.id}function w(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return r||n&&t.id===n.id&&n.isSelf?e("SavedMessages"):t.title||e("HiddenName")}function C(e){if(e.fullInfo)return e.fullInfo.about}function S(e){const{username:t}=e;if(t)return`https://t.me/${t}`;const{inviteLink:n}=e.fullInfo||{};return n}function E(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"normal";if(e.avatarHash)return"big"===t?`profile${e.id}?${e.avatarHash}`:`avatar${e.id}?${e.avatarHash}`}function P(e){return!e.lastMessage}function M(e){return Boolean(e.adminRights)}function A(e,t){return!!e.adminRights&&e.adminRights[t]}function k(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 T(e,t){return t!==r._f||!(e.isRestricted||e.migratedTo||e.isNotJoined||y(e.id))&&(!!e.isCreator||!!f(e.id)||(g(e)?A(e,"postMessages"):M(e)||!k(e,"sendMessages")))}function N(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!e)return{canAttachMedia:!1,canAttachPolls:!1,canSendStickers:!1,canSendGifs:!1,canAttachEmbedLinks:!1};const n=M(e);return{canAttachMedia:n||!k(e,"sendMedia"),canAttachPolls:(n||!k(e,"sendPolls"))&&(!f(e.id)||t),canSendStickers:n||!k(e,"sendStickers"),canSendGifs:n||!k(e,"sendGifs"),canAttachEmbedLinks:n||!k(e,"embedLinks")}}function L(e,t,n){if(null!=t&&t.sendMessages){const{untilDate:n}=t;return n&&n2&&void 0!==arguments[2]?arguments[2]:{};return n[e.id]&&void 0!==n[e.id].isMuted?n[e.id].isMuted:e.isMuted||f(e.id)&&!t.hasPrivateChatsNotifications||g(e)&&!t.hasBroadcastNotifications||h(e)&&!t.hasGroupNotifications}function F(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{hasPrivateChatsMessagePreview:r=!0,hasBroadcastMessagePreview:o=!0,hasGroupMessagePreview:d=!0}=t;return n[e.id]&&void 0!==n[e.id].shouldShowPreviews?n[e.id].shouldShowPreviews:f(e.id)&&r||g(e)&&o||h(e)&&d}function O(e){return m(e)||(p(e)||g(e))&&e.isCreator}function D(e,t,n){const{id:r,title:o,emoticon:d,description:a,pinnedChatIds:u,excludedChatIds:i,includedChatIds:s,excludeArchived:c,excludeMuted:l,excludeRead:f,...h}=t;return void 0!==n&&(Object.values(h).filter(Boolean).length>1||null!=i&&i.length||null!=s&&s.length)?e("Chats",n):h.bots?e("FilterBots"):h.groups?e("FilterGroups"):h.channels?e("FilterChannels"):h.contacts?e("FilterContacts"):h.nonContacts?e("FilterNonContacts"):void 0}function Z(e,t,n){if(n&&!f(t))return n.isSelf?e("FromYou"):(0,a.Vl)(n)}function _(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3?arguments[3]:void 0;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+=c),r&&r.includes(e)&&(d=Date.now()+l+(r.length-r.indexOf(e))),d}),"desc")}function $(e,t,n,r,o){if(!r)return t;const d=(0,i.W)(r);return t.filter((t=>{const r=n[t];return!!r&&d(w(e,r,void 0,t===o))}))}},5806:(e,t,n)=>{n.d(t,{lN:()=>F,JE:()=>T,uw:()=>Ce,k6:()=>ue,lb:()=>x,$l:()=>o.$l,kK:()=>r.kK,H5:()=>o.H5,MR:()=>ce,kw:()=>r.kw,cc:()=>o.cc,Qm:()=>o.Qm,RT:()=>o.RT,GM:()=>o.GM,hu:()=>o.hu,N0:()=>pe,Hd:()=>o.Hd,U:()=>o.U,l6:()=>o.l6,T7:()=>v,SB:()=>o.SB,VE:()=>o.VE,XV:()=>we,Sc:()=>be,N5:()=>z,oP:()=>K,qp:()=>j,w6:()=>k,R5:()=>Ie,$D:()=>p,aE:()=>Y,ep:()=>fe,c0:()=>he,d0:()=>c,eO:()=>te,Tp:()=>l,nf:()=>ne,kG:()=>le,Ti:()=>ie,DH:()=>ae,KK:()=>h,O$:()=>W,t9:()=>ee,dT:()=>R,Y5:()=>H,zF:()=>o.zF,q8:()=>o.q8,_O:()=>g,bf:()=>q,Kk:()=>_,Eb:()=>Z,MK:()=>O,UD:()=>m,EU:()=>D,b7:()=>G,kd:()=>J,s1:()=>re,F$:()=>oe,Cg:()=>de,bV:()=>ge,HV:()=>ve,zX:()=>o.zX,OU:()=>E,RI:()=>P,Ow:()=>Ee,Rs:()=>r.Rs,Vl:()=>r.Vl,Js:()=>r.Js,db:()=>r.db,Tq:()=>r.Tq,jC:()=>ye,BM:()=>me,u8:()=>V,Lo:()=>w,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:()=>I,$R:()=>N,CD:()=>A,rl:()=>Q,hC:()=>X,CI:()=>M,B4:()=>y,ss:()=>b,jM:()=>C,cS:()=>r.cS,YC:()=>o.YC,kM:()=>r.kM,Mg:()=>o.Mg,Ak:()=>f,i4:()=>o.i4,Sm:()=>o.Sm,ih:()=>o.ih,Z0:()=>r.Z0});var r=n(3311),o=n(2825),d=n(6137),a=n(3716),u=n(7361),i=n(4784);const s=new RegExp(a.FM,"i");function c(e){return`message${e.toString().replace(".","-")}`}function l(e){const{chatId:t,id:n}=e;return function(e,t){return`msg${e}-${t}`}(t,n)}function f(e){const t=e.match(/^msg(-?\d+)-(\d+)/);return{chatId:t[1],messageId:Number(t[2])}}function h(e){return e.previousLocalId||e.id}function m(e){const{text:t,sticker:n,photo:r,video:o,audio:d,voice:u,document:i,poll:s,webPage:c,contact:l,invoice:f,location:h}=e.content;return t?t.text:n||r||o||d||u||i||l||s||c||f||h?void 0:a.VC}function p(e){const{text:t,sticker:n,photo:r,video:o,audio:d,voice:a,document:u,poll:s,webPage:c,contact:l}=e.content;return!!(n||null!=o&&o.isRound)||!(!t||r||o||d||a||u||s||c||l)&&((0,i.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 v(e){const{text:t}=e.content;let n;if(null!=t&&t.entities){let e=t.entities.find((e=>e.type===d.Vv.TextUrl));if(e&&(n=e.url.match(s)),!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(s)}}if(!n&&t&&(n=t.text.match(s)),n)return{url:n[0],domain:n[3]}}function y(e){return e.isOutgoing}function b(e){return Boolean(e.replyToMessageId)}function I(e){return Boolean(e.forwardInfo)}function w(e){return Boolean(e.content.action)}function C(e){return e.chatId===a.aw&&Math.round(e.id)!==e.id}function S(e){return Boolean(e.senderId)&&!(0,o.YC)(e.senderId)&&y(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>=a.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.isLottie?"tgs":t.sticker.isVideo?"webm":(0,u.on)()?"webp":"png";return`${t.sticker.id}.${e}`}if(t.audio)return t.audio.fileName;const d=l(e);return r?`${d}.jpg`:t.voice?u.m5?`${d}.ogg`:`${d}.wav`:d}function T(e){return!e.results.some((e=>e.count>0))}function N(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now()/1e3;const{location:n}=e.content;return"geoLive"===(null==n?void 0:n.type)&&t-(e.date||0)>=n.period}var L=n(8035);function R(e){var t,n;return e.isOutgoing?null===(t=e.reactions)||void 0===t||null===(n=t.recentReactions)||void 0===n?void 0:n[0]:void 0}function x(e,t,n){if(!e||!e.recentReactions)return!0;if(!t||!t.recentReactions)return!1;if(t.recentReactions.every((e=>e.userId===n)))return!1;const r=e.results.reduce(((e,t)=>(e[t.reaction]=t.count,e)),{});return t.results.some((e=>!r[e.reaction]||r[e.reaction]2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:F,o=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],d=arguments.length>5&&void 0!==arguments[5]&&arguments[5];const a=!n&&Z(t,o),u=a?`${a} `:"",i=(0,L.Z)(D(t),r),s=_(e,t,i,o,d);return`${u}${s}`}function D(e){const t=m(e);if(!t)return;const{entities:n}=e.content.text||{};return null!=n&&n.length?n.reduce(((e,t)=>{let{type:n,offset:r,length:o}=t;if(n!==d.Vv.Spoiler)return e;const a=function(e){return new Array(e).fill(void 0).map((()=>B[Math.floor(Math.random()*B.length)])).join("")}(o);return`${e.substr(0,r)}${a}${e.substr(r+o,e.length)}`}),t):t}function Z(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const{photo:n,video:r,audio:o,voice:d,document:a,sticker:u,poll:i}=e.content;if(e.groupedId||n)return"🖼";if(r)return"📹";if(u)return u.emoji;if(o)return"🎧";if(d)return"🎤";if(a)return"📎";if(i)return"📊";const s=!t&&R(e);return s?s.reaction:void 0}function _(e,t,n){let r=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],o=arguments.length>4&&void 0!==arguments[4]&&arguments[4];const{text:d,photo:u,video:i,audio:s,voice:c,document:l,sticker:f,contact:h,poll:m,invoice:p,location:g}=t.content;let v;t.groupedId&&(v=n||e("lng_in_dlg_album")),u&&(v=n||e("AttachPhoto")),i&&(v=n||e(i.isGif?"AttachGif":"AttachVideo")),f&&(v=e("AttachSticker").trim()),s&&(v=$(t)||e("AttachMusic")),c&&(v=n||e("AttachAudio")),l&&(v=o?l.fileName:n||l.fileName),h&&(v=e("AttachContact")),m&&(v=m.summary.question),p&&(v=`${e("PaymentInvoice")}: ${p.text}`),d&&(o&&v?v+=`\n${n}`:v=n),"geo"!==(null==g?void 0:g.type)&&"venue"!==(null==g?void 0:g.type)||(v=e("Message.Location")),"geoLive"===(null==g?void 0:g.type)&&(v=e("Message.LiveLocation"));const y=!r&&R(t);return v&&y&&(v=`to your "${v}"`),v||a.VC}function $(e){const{audio:t,text:n}=e.content;return t&&[t.title,t.performer].filter(Boolean).join(" — ")||(null==n?void 0:n.text)}var U=n(5376);function j(e){return e.content}function V(e){return Boolean(W(e)||G(e)||Y(e)||q(e)||function(e){return e.content.contact}(e)||ee(e)||z(e)||K(e)||J(e))}function W(e){return e.content.photo}function G(e){return e.content.video}function H(e){const{video:t}=e.content;return null!=t&&t.isRound?t:void 0}function z(e){return e.content.action}function K(e){return e.content.audio}function J(e){return e.content.voice}function q(e){return e.content.sticker}function Y(e){return e.content.document}function Q(e){const t=Y(e);return t?"photo"===t.mediaType:void 0}function X(e){const t=Y(e);return t?"video"===t.mediaType:void 0}function ee(e){return e.content.poll}function te(e){return e.content.invoice}function ne(e){return e.content.location}function re(e){return e.content.webPage}function oe(e){var t;return null===(t=re(e))||void 0===t?void 0:t.photo}function de(e){var t;return null===(t=re(e))||void 0===t?void 0:t.video}function ae(e){var t;return null===(t=function(e){const t=W(e)||G(e)||Y(e)||q(e)||oe(e)||de(e);if(t)return t.thumbnail}(e))||void 0===t?void 0:t.dataUri}function ue(e,t,n,r,o){const{long:d,lat:a,accessHash:u,accuracyRadius:i}=e;return`staticMap:${u}?lat=${a}&long=${d}&w=${t}&h=${n}&zoom=${r}&scale=${o}&accuracyRadius=${i}`}function ie(e,t){const{photo:n,video:r,sticker:o,audio:d,voice:a,document:u}=e.content,i=oe(e),s=de(e),c=r||s,f=n||i,h=f||c||o||d||a||u;if(!h)return;const m=h.id,p=`${l(e)}${m?`:${m}`:""}`;if(c)switch(t){case"micro":case"pictogram":case"viewerPreview":return`${p}?size=m`;case"inline":return me(e)?void 0:se(c,p);case"viewerFull":return se(c,p);case"download":return`${p}?download`}if(f)switch(t){case"micro":case"pictogram":return`${p}?size=m`;case"inline":return me(e)?void 0:`${p}?size=x`;case"viewerPreview":return`${p}?size=x`;case"viewerFull":case"download":return`${p}?size=z`}if(u)switch(t){case"micro":case"pictogram":case"inline":case"viewerPreview":if(!(0,U.v6)(u)||me(e))return;return`${p}?size=m`;case"viewerFull":case"download":return p}if(o)switch(t){case"micro":return;case"pictogram":return`${p}?size=m`;case"inline":return p;case"download":return`${p}?download`}if(d)switch(t){case"micro":case"pictogram":return ce(d)?`${p}?size=m`:void 0;case"inline":return se(d,p);case"download":return`${p}?download`}if(a)switch(t){case"micro":case"pictogram":return;case"inline":return p;case"download":return`${p}?download`}}function se(e,t){return u.I_&&u.s$?`${t}?fileSize=${e.size}&mimeType=${e.mimeType}`:t}function ce(e){return e.thumbnailSizes&&e.thumbnailSizes.length>0}function le(e,t){const{sticker:n,video:r,audio:o,voice:a}=e.content,i=r||de(e);return n&&"inline"===t&&n.isLottie?d.IU.Lottie:i&&u.I_&&("viewerFull"===t||"inline"===t)?d.IU.Progressive:o||a?a&&!u.m5?d.IU.BlobUrl:d.IU.Progressive:d.IU.BlobUrl}function fe(e){const{photo:t,video:n,document:r}=e.content,o=oe(e),d=de(e);if(t||o)return`photo${e.date}.jpeg`;const{fileName:a}=n||d||r||{};return a}function he(e){const{video:t,document:n}=e.content,r=de(e),{size:o}=t||r||n||{};return o}function me(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 pe(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return Ie(e,t,n?"media":"inlineMedia")}function ge(e){return e.sizes.find((e=>"z"===e.type))||e.sizes.find((e=>"y"===e.type))||ve(e)}function ve(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 ye(e){if(e.width&&e.height)return e}function be(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const r=M(e),o=r||n,d=Number(t);return{isUploading:r,isTransferring:o,transferProgress:d}}function Ie(e,t,n){let r;switch(n){case"media":r=e=>{const t=G(e);return W(e)||t&&!t.isRound&&!t.isGif};break;case"documents":r=Y;break;case"links":r=e=>re(e)||function(e){const{text:t}=e.content,n=t&&t.text.match(s);if(n)return{url:n[0],domain:n[3]}}(e);break;case"audio":r=K;break;case"voice":r=e=>{const t=G(e);return J(e)||t&&t.isRound};break;case"inlineMedia":r=e=>{const t=G(e);return W(e)||t&&!t.isRound&&!t.isGif||Q(e)||X(e)};break;default:return[]}return t.reduce(((t,n)=>(e[n]&&r(e[n])&&t.push(n),t)),[])}function we(e){const{audio:t,voice:n,video:r}=j(e),o=t||n||r||de(e);if(o)return o.duration}function Ce(e,t){return`${e}_${t}`}const Se={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 Ee(e){const{message:t,code:n,param:r}=e,{field:o,message:d}=r?Se[r]:Se[n];return{field:o,message:d,description:t}}},3311:(e,t,n)=>{n.d(t,{Js:()=>c,NB:()=>h,Rs:()=>b,Tq:()=>l,Vl:()=>s,Z0:()=>g,cS:()=>m,db:()=>y,kK:()=>v,kM:()=>f,kw:()=>p});var r=n(3716),o=n(790),d=n(782),a=n(2267),u=n(5765);const i=[1,8,5,2,7,4,6];function s(e){if(e)switch(e.type){case"userTypeBot":case"userTypeRegular":return e.firstName||e.lastName;case"userTypeDeleted":case"userTypeUnknown":return"Deleted";default:return}}function 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),a=new Date(1e3*t);if(a>=r)return e("LastSeen.JustNow");const u=new Date(r.getTime()-a.getTime());if(u.getTime()/1e3<60)return e("LastSeen.JustNow");if(u.getTime()/1e3<3600)return e("LastSeen.MinutesAgo",Math.floor(u.getTime()/1e3/60));const i=new Date;if(i.setHours(0,0,0,0),a>new Date(i.getTime()+1e3*d))return u.getTime()/1e3<21600?e("LastSeen.HoursAgo",Math.floor(u.getTime()/1e3/60/60)):e("LastSeen.TodayAt",(0,o.mr)(e,a));const s=new Date;return s.setDate(r.getDate()-1),s.setHours(0,0,0,0),a>new Date(s.getTime()+1e3*d)?e("LastSeen.YesterdayAt",(0,o.mr)(e,a)):e("LastSeen.AtDate",(0,o.Tu)(e,a))}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){let o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0;return(0,d.Xo)(e,(e=>{const d=(0,a.b)(o);if(r&&r.includes(e))return d+172800-(r.length-r.indexOf(e));const u=t[e],i=n[e];if(!u||!i)return 0;if("userStatusOnline"===i.type)return i.expires;if("userStatusOffline"===i.type&&i.wasOnline)return i.wasOnline;switch(i.type){case"userStatusRecently":return d-86400;case"userStatusLastWeek":return d-604800;case"userStatusLastMonth":return d-18144e3;default:return 0}}),"desc")}function v(e,t,n,r,o){if(!n)return e;const d=(0,u.W)(n);return e.filter((e=>{const n=t[e];if(!n)return!1;const a=e===r?o:c(n);return a&&d(a)||d(n.username)}))}function y(e){return"number"==typeof e?Math.abs(e):Math.abs(Number(e))}function b(e){const t=e?y(e.id)%7:0;return i[t]}},3555:(e,t,n)=>{n.d(t,{R3:()=>d,Rd:()=>o,Sv:()=>a,c$:()=>i,iw:()=>u});const r=(0,n(5116).gP)(),o=r.getGlobal,d=r.setGlobal,a=r.getActions,u=r.addActionHandler,i=r.withGlobal},3475:(e,t,n)=>{n.d(t,{B1:()=>u,Dd:()=>p,GL:()=>c,Mg:()=>a,Pi:()=>h,SL:()=>i,a4:()=>s,fZ:()=>l,iX:()=>g,vv:()=>m});var r=n(3716),o=n(782),d=n(1192);function a(e,t,n){return{...e,chats:{...e.chats,listIds:{...e.chats.listIds,[t]:n}}}}function u(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:a(e,t,[...r||[],...o])}function i(e,t){return{...e,chats:{...e.chats,byId:t}}}function s(e,t,n,r){const{byId:o}=e.chats,d=f(e,t,n,r);return d?i(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=i(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=i(e,{...n,...o}):e}function f(e,t,n,r){const{byId:d}=e.chats,a=d[t],u=n.isMin&&a&&!a.isMin,i={...a,...u?(0,o.CE)(n,["isMin","accessHash"]):n,...r&&{photos:[r,...a.photos||[]]}};if(i.id&&i.type)return i}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]}})),s(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=a(e,n,r.filter((e=>e!==t)))),s(e,t,{isNotJoined:!0})}function g(e,t,n){var r;const d=null===(r=t.fullInfo)||void 0===r?void 0:r.members,a=new Set(n.map((e=>e.userId))),u=[...(null==d?void 0:d.filter((e=>!a.has(e.userId))))||[],...n],i=(null==d?void 0:d.map((e=>{let{userId:t}=e;return t})))||[],c=u.map((e=>{let{userId:t}=e;return t}));return(0,o.et)(i,c)?e:s(e,t.id,{fullInfo:{...t.fullInfo,members:u}})}},5406:(e,t,n)=>{n.d(t,{O4:()=>K,iX:()=>r.iX,c_:()=>o.c_,fZ:()=>r.fZ,m6:()=>o.m6,aK:()=>H,aJ:()=>G,zn:()=>P,Sh:()=>y,$S:()=>o.$S,bp:()=>ae,WY:()=>ue,ft:()=>M,K4:()=>o.K4,bV:()=>o.bV,GK:()=>I,M6:()=>o.M6,i9:()=>o.i9,Dd:()=>r.Dd,vy:()=>f,rB:()=>J,g_:()=>c,Mg:()=>r.Mg,SL:()=>r.SL,Pb:()=>F,w3:()=>o.w3,BI:()=>V,lr:()=>W,pf:()=>o.pf,ps:()=>E,s5:()=>m,y9:()=>o.y9,fS:()=>oe,nA:()=>ee,_7:()=>re,Q$:()=>X,Dq:()=>de,vT:()=>Q,QD:()=>ne,QH:()=>te,Ob:()=>o.Ob,a4:()=>r.a4,B1:()=>r.B1,vv:()=>r.vv,Pi:()=>r.Pi,cY:()=>o.cY,GL:()=>r.GL,Wy:()=>o.Wy,wV:()=>o.wV,cq:()=>o.cq,rq:()=>s,No:()=>k,Og:()=>T,xv:()=>L,px:()=>N,xj:()=>o.xj,c1:()=>_,z5:()=>Z,qr:()=>B,dx:()=>O,fw:()=>j,H9:()=>U,HN:()=>z,ff:()=>o.ff,P4:()=>o.P4,TM:()=>Y,Fn:()=>o.Fn,ze:()=>ie,yC:()=>se,Rg:()=>i,z3:()=>u,IM:()=>l,sN:()=>o.sN,Xg:()=>o.Xg,j6:()=>o.j6,lG:()=>o.lG,IE:()=>q,Nq:()=>g,Lm:()=>w,Q3:()=>C,eD:()=>v});var r=n(3475),o=n(4907),d=n(782),a=n(1192);function u(e,t,n,r,o){const a=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,d.ee)(a,"id")},[t]:{...e.stickers[t],hash:n,..."search"===t?{resultIds:o}:{setIds:r.map((e=>{let{id:t}=e;return t}))}}}}}function i(e,t,n){const r=e.stickers.setsById[t]||{},o=e.stickers.added.setIds||[];let d=o;return n.installedDate&&o&&!o.includes(t)&&(d=[t,...d]),!n.installedDate&&null!=o&&o.includes(t)&&(d=d.filter((e=>e!==t))),{...e,stickers:{...e.stickers,added:{...e.stickers.added,setIds:d},setsById:{...e.stickers.setsById,[t]:{...r,...n}}}}}function s(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 c(e,t){return{...e,animatedEmojis:t}}function l(e,t,n,r){const o=[...(0,a.Pk)(e,t),...n||[]],u=(0,d.Tw)(o.map((e=>{let{id:t}=e;return t}))),i=(0,d.ee)(o,"id"),s=u.map((e=>i[e]));return{...e,stickers:{...e.stickers,forEmoji:{emoji:t,stickers:s,hash:r}}}}function f(e){const{emoji:t,stickers:n,hash:r}=e.stickers.forEmoji||{};return t?l(e,t,n,r):e}var h=n(735);function m(e,t){return{...e,users:{...e.users,byId:t}}}function p(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 g(e,t,n){const{byId:r}=e.users,o=b(e,t,n);return o?m(e=p(e,[o]),{...r,[t]:o}):e}function v(e,t){const n=Object.keys(t).reduce(((n,r)=>{const o=b(e,r,t[r]);return o&&(n[r]=o),n}),{});return e=p(e=m(e,{...e.users.byId,...n}),Object.values(n))}function y(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=b(e,d,t[d]);n&&(o[d]=n,r||(r=!0))}return o}),{});return r?e=p(e=m(e,{...n,...o}),Object.values(o)):e}function b(e,t,n){const{byId:r}=e.users,o=r[t],a=n.isMin&&o&&!o.isMin,u={...o,...a?(0,d.CE)(n,["isMin","accessHash"]):n};if(u.id&&u.type)return u}function I(e,t){const{byId:n}=e.users,{userIds:o}=e.contactList||{};return e=m(e={...e,contactList:{userIds:o?o.filter((e=>e!==t)):h.D}},{...n,[t]:{...n[t],isContact:void 0}}),(0,r.a4)(e,t,{settings:void 0})}function w(e,t){return{...e,userSearch:{...e.userSearch,...t}}}function C(e,t){return w(e,{fetchingStatus:t})}function S(e,t,n){const{byId:r}=e.users,o=r[t];return o&&o.fullInfo?g(e,t,{...o,fullInfo:{...o.fullInfo,isBlocked:n}}):e}function E(e,t){return{...e,users:{...e.users,statusesById:t}}}function P(e,t){const{statusesById:n}=e.users,r=Object.keys(t).filter((e=>!n[e]));return r.length?e=E(e,{...n,...(0,d.ei)(t,r)}):e}function M(e){return{...e,newContact:void 0}}const A=e=>`${e.chatId}_${e.id}`;function k(e,t){return{...e,globalSearch:{...e.globalSearch,...t}}}function T(e,t){return k(e,{currentContent:t})}function N(e,t,n,r,o){var a;const{resultsByType:u}=e.globalSearch||{},i=t.reduce(((e,t)=>(e[A(t)]=t,e)),{}),s=null==u||null===(a=u[r])||void 0===a?void 0:a.foundIds;if(void 0!==s&&Object.keys(i).every((e=>s.includes(A(i[e])))))return L(e,{messages:!1});const c=s||[],l=t.map((e=>A(e))),f=Array.prototype.concat(c,l),h=(0,d.et)(c,f)?c:f;return k(e=L(e,{messages:!1}),{resultsByType:{...(e.globalSearch||{}).resultsByType,[r]:{totalCount:n,nextOffsetId:o,foundIds:h}}})}function L(e,t){return k(e,{fetchingStatus:{...e.globalSearch.fetchingStatus,...t}})}var R=n(5806);function x(e,t,n){return{...e,localTextSearch:{byChatThreadKey:{...e.localTextSearch.byChatThreadKey,[t]:n}}}}function B(e,t,n,r,o){const d=(0,R.uw)(t,n);return x(e,d,{...e.localTextSearch.byChatThreadKey[d],isActive:r,query:o})}function F(e,t,n,r,o,d){const a=(0,R.uw)(t,n);return x(e,a,{...e.localTextSearch.byChatThreadKey[a],results:{foundIds:r,totalCount:o,nextOffsetId:d}})}function O(e,t,n,r,o,a){const u=(0,R.uw)(t,n),{results:i}=e.localTextSearch.byChatThreadKey[u]||{},s=(null==i?void 0:i.foundIds)||[],c=$((0,d.Tw)(Array.prototype.concat(s,r)));return F(e,t,n,(0,d.et)(s,c)?s:c,o,a)}function D(e,t,n){return{...e,localMediaSearch:{byChatId:{...e.localMediaSearch.byChatId,[t]:n}}}}function Z(e,t,n){return D(e,t,{...e.localMediaSearch.byChatId[t],currentType:n})}function _(e,t,n,r,o,a){const{resultsByType:u}=e.localMediaSearch.byChatId[t]||{},i=null!=u&&u[n]?u[n].foundIds:[],s=$((0,d.Tw)(Array.prototype.concat(i,r)));return function(e,t,n,r,o,d){return D(e,t,{...e.localMediaSearch.byChatId[t],resultsByType:{...(e.localMediaSearch.byChatId[t]||{}).resultsByType,[n]:{foundIds:r,totalCount:o,nextOffsetId:d}}})}(e,t,n,(0,d.et)(i,s)?i:s,o,a)}function $(e){return e.sort(((e,t)=>t-e))}function U(e,t){return{...e,management:{...e.management,progress:t}}}function j(e,t,n){return{...e,management:{...e.management,byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t]||{},...n}}}}}function V(e,t){return{...e,settings:{...e.settings,byKey:{...e.settings.byKey,...t}}}}function W(e,t,n){return{...e,settings:{...e.settings,themes:{...e.settings.themes,[t]:{...e.settings.themes[t]||{},...n}}}}}function G(e,t){return t.forEach((t=>{const{chatId:n,...r}=t;e=H(e,n,r)})),e}function H(e,t,n){return{...e,settings:{...e.settings,notifyExceptions:{...e.settings.notifyExceptions,[t]:n}}}}function z(e,t,n,r){switch(t){case"contact":return V(e,{...void 0!==n&&{hasPrivateChatsNotifications:!n},...void 0!==r&&{hasPrivateChatsMessagePreview:r}});case"group":return V(e,{...void 0!==n&&{hasGroupNotifications:!n},...void 0!==r&&{hasGroupMessagePreview:r}});case"broadcast":return V(e,{...void 0!==n&&{hasBroadcastNotifications:!n},...void 0!==r&&{hasBroadcastMessagePreview:r}})}}function K(e,t){return e=S(e,t,!0),{...e,blocked:{...e.blocked,ids:[t,...e.blocked.ids],totalCount:e.blocked.totalCount+1}}}function J(e,t){return e=S(e,t,!1),{...e,blocked:{...e.blocked,ids:e.blocked.ids.filter((e=>e!==t)),totalCount:e.blocked.totalCount-1}}}function q(e,t){return{...e,twoFaSettings:{...e.twoFaSettings,...t}}}function Y(e,t){return{...e,payment:{...e.payment,shippingOptions:t}}}function Q(e,t){return{...e,payment:{...e.payment,requestId:t}}}function X(e,t){return{...e,payment:{...e.payment,step:t}}}function ee(e,t){if(!t.content||!t.content.invoice)return e;const{title:n,text:r,amount:o,currency:d,isTest:a,photoUrl:u}=t.content.invoice;return{...e,payment:{...e.payment,invoiceContent:{title:n,text:r,photoUrl:u,amount:o,currency:d,isTest:a}}}}function te(e,t){return{...e,payment:{...e.payment,stripeCredentials:{...t}}}}function ne(e,t){return{...e,payment:{...e.payment,smartGlocalCredentials:{...t}}}}function re(e,t){return{...e,payment:{...e.payment,...t}}}function oe(e,t){return{...e,payment:{...e.payment,confirmPaymentUrl:t}}}function de(e,t,n){if(!t||!n)return{...e,payment:{...e.payment,receipt:void 0}};const{invoice:r}=n.content,{photoUrl:o,text:d,title:a}=r||{};return{...e,payment:{...e.payment,receipt:{...t,photoUrl:o,text:d,title:a}}}}function ae(e){return{...e,payment:{}}}function ue(e){return{...e,payment:{...e.payment,isPaymentModalOpen:!1}}}function ie(e,t,n){return{...e,statistics:{byChatId:{...e.statistics.byChatId,[t]:n}}}}function se(e,t,n,r){return{...e,statistics:{byChatId:{...e.statistics.byChatId,[t]:{...e.statistics.byChatId[t]||{},[n]:r}}}}}},4907:(e,t,n)=>{n.d(t,{$S:()=>w,Fn:()=>A,K4:()=>g,M6:()=>T,Ob:()=>N,P4:()=>p,Wy:()=>u,Xg:()=>S,bV:()=>v,cY:()=>m,c_:()=>h,cq:()=>M,ff:()=>b,i9:()=>L,j6:()=>E,lG:()=>R,m6:()=>f,pf:()=>l,sN:()=>s,w3:()=>P,wV:()=>k,xj:()=>y,y9:()=>C});var r=n(6137),o=n(3716),d=n(1192),a=n(782);function u(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:r._f,d=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"thread",a=arguments.length>4?arguments[4]:void 0;const{messageLists:u}=e.messages;let i=u;if(a||o.Cg)i=t?[{chatId:t,threadId:n,type:d}]:[];else if(t){const e=u[u.length-1];e&&e.chatId===t&&e.threadId===n&&e.type===d||(i=e&&e.chatId===o.AJ?[...u.slice(0,-1),{chatId:t,threadId:n,type:d}]:[...u,{chatId:t,threadId:n,type:d}])}else i=u.slice(0,-1);return{...e,messages:{...e.messages,messageLists:i}}}function i(e,t,n){return c(e,t,{byId:n})}function s(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}}})}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 s(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,d.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,d.Zw)(e,t)||{},a={...o[n],...r};return a.id?i(e,t,{...o,[n]:a}):e}function p(e,t,n,r){const o=(0,d.Fn)(e,t)||{},a={...o[n],...r};return a.id?P(e,t,{...o,[n]:a}):e}function g(e,t,n){const r=(0,d.Zw)(e,t);if(!r)return e;const o=(0,a.CE)(r,n),s=Object.values((0,a.q0)(r,n)).filter((e=>{let{forwardInfo:t}=e;return null==t?void 0:t.isLinkedChannelPost}));if(Object.keys(e.messages.byChatId[t].threadsById).map(Number).forEach((r=>{const o=(0,d.tZ)(e,t,r);let a=(0,d.gb)(e,t,r),u=(0,d.qC)(e,t,r),i=(0,d.Cb)(e,t,r),s=(0,d.KB)(e,t),c=null==o?void 0:o.messagesCount;n.forEach((e=>{a&&a.includes(e)&&(a=a.filter((t=>t!==e)),void 0!==c&&(c-=1)),u&&u.includes(e)&&(u=u.filter((t=>t!==e))),i&&i.includes(e)&&(i=i.filter((t=>t!==e))),s&&s.includes(e)&&(s=s.filter((t=>t!==e)))})),e=l(e,t,r,"listedIds",a),e=l(e,t,r,"outlyingIds",u),e=l(e,t,r,"viewportIds",i),e=l(e,t,r,"pinnedIds",s),o&&void 0!==c&&(e=l(e,t,r,"threadInfo",{...o,messagesCount:c}))})),s.length){const n=(0,d.Bt)(e),r=n&&n.chatId===t&&"thread"===n.type,o=null==n?void 0:n.threadId;s.forEach((n=>{const{fromChatId:a,fromMessageId:i}=n.forwardInfo,s=(0,d.hj)(e,a,i);r&&o===i&&(e=u(e,t)),s&&(e=m(e,a,i,{threadInfo:void 0}))}))}return e=i(e,t,o)}function v(e,t,n){const o=(0,d.Fn)(e,t);if(!o)return e;const u=(0,a.CE)(o,n);let i=(0,d.qy)(e,t);return i&&(n.forEach((e=>{i.includes(e)&&(i=i.filter((t=>t!==e)))})),e=l(e,t,r._f,"scheduledIds",i)),P(e,t,u)}function y(e,t,n,r){const o=(0,d.gb)(e,t,n),a=null!=o&&o.length?r.filter((e=>!o.includes(e))):r;return o&&!a.length?e:l(e,t,n,"listedIds",I([...o||[],...a]))}function b(e,t,n,r){const o=(0,d.qC)(e,t,n),a=null!=o&&o.length?r.filter((e=>!o.includes(e))):r;return o&&!a.length?e:l(e,t,n,"outlyingIds",I([...o||[],...a]))}function I(e){return e.sort(((e,t)=>e-t))}function w(e,t,n,r){const a=(0,d.Cb)(e,t,n)||[];return a.includes(r)?e:l(e,t,n,"viewportIds",I([...a.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){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],o=arguments.length>4&&void 0!==arguments[4]&&arguments[4];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,u,i){let s=arguments.length>7&&void 0!==arguments[7]&&arguments[7];const{selectedMessages:c}=e;u&&(i=(0,d.xH)(e,t,u));const l=i||[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(s&&f.length){const u=(0,d.$W)(e,t,n,r),i=u.indexOf(f[f.length-1]),s=u.indexOf(o),c=Math.min(i,s),l=Math.max(i,s),m=u.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:a,fromChatId:u}=t.forwardInfo||{};if(a&&u){const t=(0,d.tZ)(e,n,a);t&&(e=l(e,n,a,"threadInfo",{...t,lastMessageId:r,messagesCount:t.messagesCount+(o?-1:1)}))}return e}},4342:(e,t,n)=>{n.d(t,{DI:()=>b,Ek:()=>g,FM:()=>i,IK:()=>f,Mw:()=>v,N:()=>p,P_:()=>c,UW:()=>I,YK:()=>l,Z1:()=>u,_5:()=>w,ep:()=>y,g4:()=>m,pk:()=>h,xo:()=>s});var r=n(6137),o=n(5806),d=n(6087),a=n(3716);function u(e,t){return e.chats.byId[t]}function i(e,t){return t===e.currentUserId}function s(e,t){const n=function(e,t){const n=(0,o.zX)(t);return!!n&&(0,d.dy)(e,n)}(e,t);return n&&(0,o.cS)(n)}function c(e){return Object.values(e.chats.byId).find((e=>{let{isSupport:t}=e;return t}))}function l(e,t){if(!(0,o.YC)(t.id)&&!(0,o.eA)(t)&&t.fullInfo)return t.fullInfo.members&&t.fullInfo.members.length!==a.mo?t.fullInfo.members.reduce(((t,n)=>{let{userId:r}=n;return r!==e.currentUserId&&e.users.byId[r]&&(0,o.kM)(e.users.byId[r],e.users.statusesById[r])?t+1:t}),0):t.fullInfo.onlineCount}function f(e,t){const n=u(e,t),r=n&&(0,o.zX)(n),a=r&&(0,d.dy)(e,r);if(a&&(0,o.cS)(a))return a}function h(e,t){const n=u(e,t),d=f(e,t);if(!n||!d)return!1;if(n.lastMessage&&(0,o.CD)(n.lastMessage))return!0;const a=e.messages.byChatId[t];if(!a)return!1;const{listedIds:i}=a.threadsById[r._f]||{};return i&&!i.length}function m(e){return Boolean(e.chats.listIds.active)}function p(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 g(e,t){const n=u(e,t);if(n&&p(e,t))return n.folderId===a.WS?"archived":"active"}function v(e,t){return e.chatFolders.byId[t]}function y(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:a.Nf;const{active:r,archived:o}=e.chats.orderedPinnedIds;if(n===a.Nf)return Boolean(null==r?void 0:r.includes(t));if(n===a.WS)return Boolean(null==o?void 0:o.includes(t));const{byId:d}=e.chatFolders,{pinnedChatIds:u}=d[n]||{};return Boolean(null==u?void 0:u.includes(t))}function b(e,t){const n=t.toLowerCase();return Object.values(e.chats.byId).find((e=>e.username&&e.username.toLowerCase()===n))}function I(e){return Boolean(u(e,a.aw))}function w(e,t){var n;const r=u(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)||u(e,o):void 0}},1192:(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=>i.dy,Bk:()=>i.Bk,ss:()=>i.ss,Cb:()=>x,P2:()=>Fe});var r=n(1713),o=n(7361),d=n(6137),a=n(3716),u=n(4342),i=n(6087),s=n(5806),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((e=>{let{packs:n}=e;n&&(r=r.concat(n[t]||[],n[g(t)]||[]))})),r}function g(e){return e.replace("️","")}function v(e,t){const{animatedEmojis:n}=e;if(!n||!n.stickers)return;const r=g(t);return n.stickers.find((e=>e.emoji===t||e.emoji===r))}function y(e,t){const{animatedEmojiEffects:n}=e;if(!n||!n.stickers)return;const r=g(t);return n.stickers.find((e=>e.emoji===t||e.emoji===r))}function b(e,t){var n;return null==e||null===(n=e.appConfig)||void 0===n?void 0:n.emojiSounds[g(t)]}function I(e,t){const n=g(t);return"🍑"===n?"Peach":"🍆"===n?"Eggplant":void 0}function w(e){return"Eggplant"===e?"Cumshot":void 0}function C(e){return"Cumshot"===e?"🍆":void 0}var S=n(2267),E=n(735);function P(e){const{messageLists:t}=e.messages;if(t.length)return t[t.length-1]}function M(e){const{chatId:t}=P(e)||{};return t?(0,u.Z1)(e,t):void 0}function A(e,t){var n;return null===(n=e.messages.byChatId[t])||void 0===n?void 0:n.byId}function k(e,t){var n;return null===(n=e.scheduledMessages.byChatId[t])||void 0===n?void 0:n.byId}function T(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 N(e,t,n){return T(e,t,n,"listedIds")}function L(e,t,n){return T(e,t,n,"outlyingIds")}function R(e,t,n,r){switch(r){case"thread":return x(e,t,n);case"pinned":return B(e,t);case"scheduled":return F(e,t)}}function x(e,t,n){return T(e,t,n,"viewportIds")}function B(e,t){return T(e,t,d._f,"pinnedIds")}function F(e,t){return T(e,t,d._f,"scheduledIds")}function O(e,t,n){return T(e,t,n,"scrollOffset")}function D(e,t,n){return T(e,t,n,"replyingToId")}function Z(e,t,n){return T(e,t,n,"editingId")}function _(e,t,n){return T(e,t,n,"editingDraft")}function $(e,t){return T(e,t,d._f,"editingScheduledId")}function U(e,t){return T(e,t,d._f,"editingScheduledDraft")}function j(e,t,n){return T(e,t,n,"draft")}function V(e,t,n){return T(e,t,n,"noWebPage")}function W(e,t,n){return T(e,t,n,"threadInfo")}function G(e,t,n){return T(e,t,n,"firstMessageId")}function H(e,t,n){return T(e,t,n,"replyStack")}function z(e,t,n){if(n===d._f)return(0,u.Z1)(e,t);const r=W(e,t,n);return r?(0,u.Z1)(e,r.originChannelId||t):void 0}function K(e,t,n){if(n===d._f)return;const r=W(e,t,n);return r?r.topMessageId:void 0}function J(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 q(e,t,n){const r=P(e);if(!r)return!1;const{threadInfo:o}=J(e,t,n)||{};return t===r.chatId&&(r.threadId===d._f||o&&r.threadId===o.threadId)}function Y(e,t,n){const r=x(e,t,n);if(!r||!r.length)return!0;let o;if(n===d._f){const n=(0,u.Z1)(e,t);if(!n||!n.lastMessage)return!0;o=n.lastMessage.id}else{const r=W(e,t,n);if(!r||!r.lastMessageId)return;o=r.lastMessageId}return o>=a.AE&&!Q(e,t,o)||r[r.length-1]>=o}function Q(e,t,n){const r=A(e,t);return r?r[n]:void 0}function X(e,t,n){const r=k(e,t);return r?r[n]:void 0}function ee(e,t,n,r){if("scheduled"===r){const n=$(e,t);return n?X(e,t,n):void 0}{const r=Z(e,t,n);return r?Q(e,t,r):void 0}}function te(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 ne(e,t){const{chatId:n,messageId:r}=e.focusedMessage||{};return n===t?r:void 0}function re(e,t){const n=ne(e,t.chatId);return!!n&&(n===t.id||n===t.previousLocalId)}function oe(e,t){const{lastReadOutboxMessageId:n}=(0,u.Z1)(e,t.chatId)||{};return(0,s.CI)(t)||!n||n2&&void 0!==arguments[2]&&arguments[2];return oe(e,t)||n?(0,s.RI)(t):"read"}function ae(e,t){const{senderId:n}=t;if(n)return(0,s.YC)(n)?(0,i.dy)(e,n):(0,u.Z1)(e,n)}function ue(e,t){const{forwardInfo:n}=t;if(n)return n.isChannelPost&&n.fromChatId?(0,u.Z1)(e,n.fromChatId):n.senderUserId?(0,i.dy)(e,n.senderUserId)||(0,u.Z1)(e,n.senderUserId):void 0}function ie(e,t,n){var r,o,d,a,i;const c=(0,u.Z1)(e,t.chatId);if(!c||c.isRestricted)return{};const l=(0,s.YC)(c.id),f=(0,u.FM)(e,t.chatId),h=(0,s.G9)(c),m=(0,s.ZV)(c),p=(0,s.eA)(c),g=(0,s.CI)(t),v=(0,s.jM)(t),y=(0,s.B4)(t),b=(0,s.Lo)(t),{content:I}=t,w=(f||m&&(0,s.VE)(c,"pinMessages")||p&&(0,s.VE)(c,"editMessages")||(0,S.b)(e.serverTimeOffset)-t.date<172800)&&!(I.sticker||I.contact||I.poll||I.action||I.audio||null!==(r=I.video)&&void 0!==r&&r.isRound||I.location)&&!(0,s.MF)(t)&&!t.viaBotId,C=!g&&!v&&(0,s.Qm)(c,n),E=l||c.isCreator||!p&&!(0,s.Mg)(c,"pinMessages")||(0,s.VE)(c,"pinMessages");let P=!g&&!v&&!b&&E,M=!1;const A=B(e,c.id);P&&(M=Boolean(A&&A.includes(t.id)),P=!M);const k=!g&&!v&&(l||y||h||c.isCreator||(0,s.VE)(c,"deleteMessages")),T=!l&&!y,N=k&&(l&&!f||h&&(y||(0,s.VE)(c,"deleteMessages")||c.isCreator)),L=!g&&!b&&w&&(y||p&&(c.isCreator||(0,s.VE)(c,"editMessages"))),R=!g&&!b,x=Boolean(t.content.sticker),F=x&&function(e,t){const{stickers:n}=e.stickers.favorite;return n&&n.some((e=>{let{id:n}=e;return n===t.id}))}(e,t.content.sticker),O=!b&&x&&!F,D=!b&&F,Z=!b,_=!b&&(p||m),$=!b,U=Boolean((null===(o=I.webPage)||void 0===o?void 0:o.document)||(null===(d=I.webPage)||void 0===d?void 0:d.video)||(null===(a=I.webPage)||void 0===a?void 0:a.photo)||I.audio||I.voice||I.photo||I.video||I.document||I.sticker),j=null===(i=t.content.video)||void 0===i?void 0:i.isGif;return{noOptions:[C,L,P,M,T,k,N,R,O,D,Z,_,$,U,j].every((e=>!e)),canReply:C,canEdit:L,canPin:P,canUnpin:M,canReport:T,canDelete:k,canDeleteForAll:N,canForward:R,canFaveSticker:O,canUnfaveSticker:D,canCopy:Z,canCopyLink:_,canSelect:$,canDownload:U,canSaveGif:j}}function se(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=P(e)||{},o=n&&A(e,n);if(!o||!t||!r)return{};const d=t.map((t=>o[t]&&ie(e,o[t],r))).filter(Boolean);return{canDelete:d.every((e=>e.canDelete)),canDeleteForAll:d.every((e=>e.canDeleteForAll))}}function ce(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=P(e)||{},o=n&&A(e,n);return!!(o&&t&&r)&&t.map((t=>o[t]&&ie(e,o[t],r))).filter(Boolean).every((e=>e.canReport))}function le(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=P(e)||{},o=n&&A(e,n);return!!(o&&t&&r)&&t.map((t=>o[t]&&ie(e,o[t],r))).filter(Boolean).some((e=>e.canDownload))}function fe(e,t){const n=e.activeDownloads.byChatId[t.chatId];return!!n&&n.includes(t.id)}function he(e,t){return e.activeDownloads.byChatId[t]||E.D}function me(e,t){var n;return null===(n=e.fileUploads.byMessageLocalId[t.previousLocalId||t.id])||void 0===n?void 0:n.progress}function pe(e,t,n){if(n===d._f){const n=(0,u.Z1)(e,t);if(!n)return;if(!n.lastReadInboxMessageId)return;return n.lastMessage?(0,s.CI)(n.lastMessage)?n.lastMessage.id:Math.min(n.lastMessage.id,n.lastReadInboxMessageId):n.lastReadInboxMessageId}{const r=W(e,t,n);if(!r)return;return r.lastReadInboxMessageId?Math.min(r.lastReadInboxMessageId,r.lastMessageId||1/0):r.topMessageId}}function ge(e,t,n){const r=(0,u.Z1)(e,t);if(n===d._f){if(!r)return}else{const r=W(e,t,n);if(!r||void 0!==r.lastMessageId&&r.lastMessageId===r.lastReadInboxMessageId)return}const o=L(e,t,n),i=N(e,t,n),s=A(e,t);if(!s||!o&&!i)return;const c=pe(e,t,n);if(!c&&r&&r.isNotJoined)return;const l=t===a.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)&&s[e]&&(!s[e].isOutgoing||s[e].isFromScheduled)&&e>l))}if(o){const e=f(o);if(e)return e}if(i){const e=f(i);if(e)return e}}function ve(e){const{forwardMessages:t}=e;return Boolean(t.isModalShown)}function ye(e,t){const n=Object.values(e.chats.byId).find((e=>(0,s.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,u.Z1)(e,n);return o&&(0,s.Ru)(o)&&r[o.id].byId[t]}))}function be(e){const{selectedMessages:t}=e;return Boolean(t)}function Ie(e,t){const{messageIds:n}=e.selectedMessages||{};return!!n&&n.includes(t)}function we(e,t,n){const r=A(e,t);if(r)return Object.values(r).filter((e=>e.groupedId===n&&e.forwardInfo)).map((e=>{let{forwardInfo:t}=e;return t.fromMessageId}))}function Ce(e,t,n){const r=A(e,t);if(r)return Object.keys(r).map(Number).filter((e=>r[e].groupedId===n))}function Se(e,t,n){const{messageIds:r}=e.selectedMessages||{};if(!r)return!1;const o=Ce(e,t,n);return o&&o.every((e=>r.includes(e)))}function Ee(e){const{messageIds:t}=e.selectedMessages||{};return t?t.length:0}function Pe(e,t){const n=(0,u.Z1)(e,t);if(!n)return;if(!(0,u.xo)(e,n))return;const r=A(e,t),o=x(e,t,d._f);if(!r||!o)return;const a=(0,c.dF)(o,(e=>!r[e].isOutgoing&&Boolean(r[e].keyboardButtons))),i=(0,c.dF)(o,(e=>Boolean(r[e].shouldHideKeyboardButtons)));return a&&i&&i>a?void 0:a?r[a]:void 0}function Me(e,t){const n=(0,u.Z1)(e,t.chatId);if(!n)return;const r=ae(e,t),o=Boolean((0,s.O$)(t)||(0,s.F$)(t)),d=Boolean((0,s.b7)(t)||(0,s.Cg)(t)),a=Boolean((0,s.oP)(t)||(0,s.kd)(t)||(0,s.aE)(t)),{canAutoLoadPhotoFromContacts:i,canAutoLoadPhotoInPrivateChats:c,canAutoLoadPhotoInGroups:l,canAutoLoadPhotoInChannels:f,canAutoLoadVideoFromContacts:h,canAutoLoadVideoInPrivateChats:m,canAutoLoadVideoInGroups:p,canAutoLoadVideoInChannels:g,canAutoLoadFileFromContacts:v,canAutoLoadFileInPrivateChats:y,canAutoLoadFileInGroups:b,canAutoLoadFileInChannels:I}=e.settings.byKey;return o?Ae({global:e,chat:n,sender:r,canAutoLoadMediaFromContacts:i,canAutoLoadMediaInPrivateChats:c,canAutoLoadMediaInGroups:l,canAutoLoadMediaInChannels:f}):d?Ae({global:e,chat:n,sender:r,canAutoLoadMediaFromContacts:h,canAutoLoadMediaInPrivateChats:m,canAutoLoadMediaInGroups:p,canAutoLoadMediaInChannels:g}):!a||Ae({global:e,chat:n,sender:r,canAutoLoadMediaFromContacts:v,canAutoLoadMediaInPrivateChats:y,canAutoLoadMediaInGroups:b,canAutoLoadMediaInChannels:I})}function Ae(e){let{global:t,chat:n,sender:r,canAutoLoadMediaFromContacts:o,canAutoLoadMediaInPrivateChats:d,canAutoLoadMediaInGroups:a,canAutoLoadMediaInChannels:u}=e;const c=Boolean(r&&(r.id===t.currentUserId||(0,i.nM)(t,r)));return Boolean(c&&o||!c&&d&&(0,s.YC)(n.id)||a&&(0,s.Bf)(n)||u&&(0,s.eA)(n))}function ke(e,t){const n=(0,s.b7)(t)||(0,s.Cg)(t);if(!n)return;const{canAutoPlayVideos:r,canAutoPlayGifs:o}=e.settings.byKey,d=n.isGif||n.isRound;return r&&!d||o&&d}function Te(e){return e.settings.byKey.shouldLoopStickers}function Ne(e){const{serviceNotifications:t}=e,n=Math.max(...t.map((e=>{let{id:t}=e;return t})));return t.find((e=>{let{id:t}=e;return t===n}))}function Le(e,t){var n;return!!t&&(t.isProtected||(null===(n=(0,u.Z1)(e,t.chatId))||void 0===n?void 0:n.isProtected))}function Re(e,t,n){var r;if(null!==(r=(0,u.Z1)(e,t))&&void 0!==r&&r.isProtected)return!0;if(!n)return!1;const o=A(e,t);return n.some((e=>{var t;return null===(t=o[e])||void 0===t?void 0:t.isProtected}))}function xe(e,t){const n=(0,u.Z1)(e,t),r=n&&(0,s.eA)(n)?e.messages.sponsoredByChatId[t]:void 0;return r&&r.expiresAt>=Math.round(Date.now()/1e3)?r:void 0}function Be(e,t){var n,r,o;if(t===a.aw)return;const d=(0,s.YC)(t),i=null===(n=e.appConfig)||void 0===n?void 0:n.defaultReaction,{availableReactions:c}=e;if(!i||null==c||!c.some((e=>e.reaction===i&&!e.isInactive)))return;if(d)return i;const l=null===(r=(0,u.Z1)(e,t))||void 0===r||null===(o=r.fullInfo)||void 0===o?void 0:o.enabledReactions;return null!=l&&l.includes(i)?i:void 0}function Fe(e){const{chatId:t,threadId:n}=P(e)||{};if(!t||!n)return;const r=T(e,t,n,"viewportIds");return r?r.map((n=>{const{senderId:r}=Q(e,t,n)||{};return r?(0,i.dy)(e,r):void 0})).filter(Boolean):void 0}function Oe(e){var t;return"scheduled"===(null===(t=P(e))||void 0===t?void 0:t.type)}function De(e,t){var n;const r=(0,u.FM)(e,t),o=t===a.FV&&(0,u.IK)(e,t);return Boolean(!r&&!o&&(0,s.YC)(t)&&(null===(n=(0,i.ss)(e,t))||void 0===n?void 0:n.wasOnline))}function Ze(e){const{chatId:t,threadId:n}=P(e)||{};if(!t||!n)return;const r=(0,s.uw)(t,n),o=e.localTextSearch.byChatThreadKey[r];return o&&o.isActive?o:void 0}function _e(e){const{chatId:t}=P(e)||{};if(t)return e.localMediaSearch.byChatId[t]}function $e(e,t){return e.statistics.byChatId[t]}function Ue(e,t){return e.management.byChatId[t]}function je(e){const{chatId:t,threadId:n}=P(e)||{};if(!t||!n)return;if((0,s.YC)(t))return"user";const r=(0,u.Z1)(e,t);return r?(0,s.Bf)(r)?"group":"channel":void 0}function Ve(e){const{mediaViewer:t}=e;return Boolean(t.messageId||t.avatarOwnerId)}function We(e){return function(e){const{pollResults:t}=e;return Boolean(t.messageId)}(e)?r.qt.PollResults:!o.wB&&Ze(e)?r.qt.Search:function(e){const{chatId:t,threadId:n}=P(e)||{};if(!t||!n)return;const r=e.management.byChatId[t];return r&&r.isActive?r:void 0}(e)?r.qt.Management:function(e){var t;if(!e.isStatisticsShown)return!1;const{chatId:n}=P(e)||{},r=n?(0,u.Z1)(e,n):void 0;return null==r||null===(t=r.fullInfo)||void 0===t?void 0:t.canViewStatistics}(e)?r.qt.Statistics:void 0!==l(e).query?r.qt.StickerSearch:void 0!==f(e).query?r.qt.GifSearch:e.newChatMembersProgress!==r.WB.Closed?r.qt.AddingMembers:e.isChatInfoShown&&P(e)?r.qt.ChatInfo:void 0}function Ge(e){return void 0!==We(e)}function He(e){const{theme:t,shouldUseSystemTheme:n}=e.settings.byKey;return n?(0,o.vn)():t}function ze(e){return e.globalSearch.query}function Ke(e){return e.payment.chatId}function Je(e){return e.payment.messageId}function qe(e){return e.payment.formId}function Ye(e){return e.payment.requestId}function Qe(e){var t;return null===(t=e.payment.nativeParams)||void 0===t?void 0:t.publishableKey}function Xe(e){var t;return null===(t=e.payment.nativeParams)||void 0===t?void 0:t.publicToken}function et(e){return e.payment.stripeCredentials}function tt(e){return e.payment.smartGlocalCredentials}function nt(e){return e.settings.byKey}function rt(e){return e.settings.notifyExceptions}},6087:(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 a(e,t){const n=t.replace(/[^0-9]/g,"");return Object.values(e.users.byId).find((e=>(null==e?void 0:e.phoneNumber)===n))}function u(e,t){return e.contactList&&e.contactList.userIds.includes(t.id)}n.d(t,{Bk:()=>a,dy:()=>r,nM:()=>u,s4:()=>d,ss:()=>o})},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=function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];const[t,n]=(0,r.eJ)(e),o=(0,r.I4)((()=>{n(!0)}),[]),d=(0,r.I4)((()=>{n(!1)}),[]);return[t,o,d]}},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,{YW:()=>s,ZP:()=>c,zG:()=>i});var r=n(4050);const o="tt-event-heavy-animation-start",d="tt-event-heavy-animation-end";let a,u=!1;function i(){return u}function s(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;function t(){a&&(clearTimeout(a),a=void 0),u=!1,document.dispatchEvent(new Event(d))}return u||(u=!0,document.dispatchEvent(new Event(o))),a&&(clearTimeout(a),a=void 0),a=window.setTimeout(t,e),t}const c=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];(0,r.d4)((()=>{if(!n)return u&&e(),document.addEventListener(o,e),document.addEventListener(d,t),()=>{document.removeEventListener(d,t),document.removeEventListener(o,e)}}),[n,t,e])}},6590:(e,t,n)=>{n.d(t,{Oy:()=>i,Wv:()=>l,ZP:()=>h});var r=n(4050),o=n(7361),d=n(7204),a=n(3555),u=n(782);const i=window.location.hash,s=`${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){let i=arguments.length>4&&void 0!==arguments[4]&&arguments[4],l=arguments.length>5?arguments[5]:void 0;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)([]),v=(0,d.Z)(l),y=(0,r.sO)(!1),b=(0,r.I4)((function(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(l){const e=v||[];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(y.current)y.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((e=>{let{index:t}=e;c.currentIndexes.splice(c.currentIndexes.indexOf(t),1)}))}l.length>0&&setTimeout((()=>{const e=++c.currentIndex;c.currentIndexes[c.currentIndexes.length-1]=e,window.history.replaceState({index:e,state:o},"",`${s}#${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&&!i?"replaceState":"pushState"]({index:e,state:o},""),f.current=e,i&&(c.nextStateIndexToReplace=c.currentIndex+1)}),0)),!t&&e||p.current||(f.current!==c.currentIndex&&i||(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,v,i]);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&&(y.current=!0,g.current.pop()),c.currentIndexes.splice(c.currentIndexes.indexOf(r),1),t&&(c.isEdge&&(0,a.Sv)().disableHistoryAnimations(),t(!c.isEdge),p.current=!0)):o===r&&p.current&&n&&!l&&(h.current=!0,c.isEdge&&(0,a.Sv)().disableHistoryAnimations(),n(e.state.state))}catch(e){}},o=l?!v||!(0,u.et)(v,l):m!==e;return!c.isDisabled&&o&&b(),window.addEventListener("popstate",r),()=>window.removeEventListener("popstate",r)}),[o,b,l,e,t,n,v,m,i]),{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},"",s)},2313:(e,t,n)=>{n.d(t,{Z:()=>o});var r=n(4050);const o=(e,t,n,o,d)=>{const[a,u]=(0,r.eJ)(-1);return(0,r.d4)((()=>{u(-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(a);if(38!==t.keyCode&&40!==t.keyCode)return;const d=document.activeElement,i=Array.from(o?r.querySelectorAll(o):r.children);let s=d&&i.indexOf(d)||a;if(38===t.keyCode&&s>0)s--;else if(40===t.keyCode&&s{n.d(t,{Z:()=>a});var r=n(711),o=n(5326),d=n(9290);const a=()=>{const e=(0,o.Z)();return(0,d.Z)((()=>r.ll(e)),[e]),r.i0}},8778:(e,t,n)=>{n.d(t,{Z:()=>a});var r=n(4050),o=n(9203),d=n(5326);const a=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],a=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const u=(0,o.o5)(e,t),i=(0,d.Z)();return(0,r.d4)((()=>{if(a)return(0,o.Qt)(i)}),[a,i]),(0,r.d4)((()=>{n||u||(0,o.$y)(e,t).then(i)}),[e,i,u,t,n]),u}},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=function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],d=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"fast",a=arguments.length>4&&void 0!==arguments[4]&&arguments[4];const[u,i]=(0,r.eJ)(!e),s=(0,r.sO)(),[c,l]=(0,r.eJ)(e&&n);if(e)i(!1),l(!0),s.current&&(window.clearTimeout(s.current),s.current=void 0);else if(l(!1),!u&&!s.current){const e=()=>{i(!0),t&&t(),s.current=void 0};a?e():s.current=window.setTimeout(e,350)}const f=c&&!(a&&!e),h=Boolean(s.current),m=e||h,p=(0,o.Z)(d&&"opacity-transition",d,f&&"open",m&&"shown",h&&"closing");return{shouldRender:m,transitionClassNames:p}}},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:()=>i,lQ:()=>m,xg:()=>s});var r=n(3716);const o=new Set(["scroll","mouseenter","mouseleave"]),d={},a={},u=new Map;function i(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const o=c(t,e);l(o,e,r)?f(o,e,n):e.addEventListener(o,n,r)}function s(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const o=c(t,e);l(o,e,r)?h(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,n){d[e]||(d[e]=0,document.addEventListener(e,p)),function(e){return a[e]||(a[e]=new Map),a[e]}(e).set(t,n),function(e){const t=u.get(e);if(t)return t;const n=new Set;return u.set(e,n),n}(t).add(e),d[e]++}function h(e,t){d[e]--,d[e]||document.removeEventListener(e,p),a[e].delete(t),u.get(t).delete(e)}function m(e){const t=u.get(e);t&&(t.forEach((t=>h(t,e))),u.delete(e))}function p(e){const t=a[e.type];if(t){let n=!1,r=e.target;const o=()=>{n=!0},d=()=>{e.preventDefault()},a=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(a),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(a).length,r=Object.values(a).reduce(((e,t)=>e+t.size),0),o=u.size,i=Array.from(u.values()).reduce(((e,t)=>e+t.size),0);console.warn("DELEGATED EVENTS STATS",{delegatedHandlersCount1:t,delegatedHandlersCount2:r,delegatedEventTypesCount:i,delegationRegistriesCount:n,delegationElementsCount:o,documentListenersCount:e})}))},2916:(e,t,n)=>{n.d(t,{Z:()=>w});var r=n(4050),o=n(6926),d=n(3716),a=n(5247),u=n(782);const i=new Set(["key","ref","teactFastList","teactOrderKey"]),s=new Set(["dir","role"]),c={autoPlay:"autoplay",autoComplete:"autocomplete"},l={};function f(e,t,n,o,a){let{skipComponentUpdate:u=!1,forceIndex:i=!1,fragment:s,moveDirection:c}=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{};const l=t&&(0,r.op)(t),f=n&&(0,r.op)(n);if(!u&&l&&f&&!(0,r.k)(t,n)&&(n=m(t,n)),!u&&f&&n.componentInstance.isMounted&&p(n,o,a,e),t===n)return n;if(d.eM&&n){const e=(0,r.U9)(n);if(e&&(!t||e!==(0,r.U9)(t)))throw new Error("[Teact] Cached virtual element was moved within tree")}if(!t&&n){f&&(n=h(n,o,a,e));const t=g(n);(0,r.CD)(n,t),i&&e.childNodes[a]?e.insertBefore(t,e.childNodes[a]):(s||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)){f&&(n=h(n,o,a,e));const d=g(n);(0,r.CD)(n,d),e.replaceChild(d,(0,r.U9)(t)),(0,r.Zb)(t)}else{const o=l&&f,d=(0,r.U9)(t);if(o||((0,r.CD)(n,d),(0,r.CD)(t,void 0),"props"in t&&"props"in n&&(n.props.ref=t.props.ref)),(0,r.O_)(n)){if(c){const t=d,n=e.childNodes["up"===c?a:a+1];n?e.insertBefore(t,n):(s||e).appendChild(t)}o||b(t,n,d),n.children=v(t,n,o?e:d)}}return n}function h(e,t,n,o){if(!(0,r.op)(e))return e;const{componentInstance:d}=e;if(!d.isMounted){p(e=(0,r.Hb)(d),t,n,o);const a=e.children[0];(0,r.op)(a)&&(e.children=[h(a,e,0,o)]),d.isMounted=!0}return e}function m(e,t){return e.componentInstance.props=t.componentInstance.props,(0,r.SO)(e.componentInstance)}function p(e,t,n,r){const{componentInstance:o}=e;o.onUpdate=()=>{t.children[n]=f(r,t.children[n],o.$element,t,n,{skipComponentUpdate:!0})}}function g(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 g(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.entries(n).forEach((e=>{let[t,r]=e;void 0!==n[t]&&I(d,t,r)})),e.children=o.map(((t,n)=>f(d,void 0,t,e,n))),d}function v(e,t,n){if(d.eM&&function(e){const t=e[0];if(t&&"props"in t&&void 0!==t.props.key){const t=e.reduce(((e,t)=>("props"in t&&t.props.key&&e.push(t.props.key),e)),[]);if(t.length!==(0,u.Tw)(t).length)throw new Error("[Teact] Children keys are not unique")}}(t.children),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 a=0;const u=e.children.reduce(((e,r,d)=>{let u="props"in r?r.props.key:void 0;const i=null!=u;if(i&&!o.has(u))return f(n,r,void 0,t,-1),e;if(!i){const o=t.children[d],a=o&&"props"in o?o.props.key:void 0;if(!o||a)return f(n,r,void 0,t,-1),e;u=`__indexKey#${d}`}return e[u]={$element:r,index:a++,order:"props"in r?r.props.teactOrderKey:void 0},e}),{});let i,s,c=[],l=0;return t.children.forEach(((e,r)=>{const o="props"in e?e.props.key:`__indexKey#${r}`,d=u[o];if(!d)return i||(i=[],s=r),void i.push(e);i&&(c=c.concat(y(i,s,n,t)),s=void 0,i=void 0);const a="props"in e?e.props.teactOrderKey:void 0,h=d.index!==l&&d.order!==a,m=h&&l>d.index;h&&!m||l++,c.push(f(n,d.$element,e,t,r,{forceIndex:!0,moveDirection:h?m?"down":"up":void 0}))})),i&&(c=c.concat(y(i,s,n,t))),c}(e,t,n);const o=e.children.length,a=t.children.length,i=Math.max(o,a),s=[],c=a>o+1?document.createDocumentFragment():void 0;for(let r=0;r=o?{fragment:c}:void 0);d&&s.push(d)}return c&&n.appendChild(c),s}function y(e,t,n,r){if(1===e.length)return[f(n,void 0,e[0],r,t,{forceIndex:!0})];if(e.length>1){const o=document.createDocumentFragment(),d=e.map((e=>f(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 b(e,t,n){const r=Object.entries(e.props),o=Object.entries(t.props);r.forEach((e=>{let[r,o]=e;const 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,a.xg)(e,t,n,t.endsWith("Capture")):t.startsWith("data-")||t.startsWith("aria-")||s.has(t)?e.removeAttribute(t):i.has(t)||delete e[c[t]||t]}(n,r,o)})),o.forEach((t=>{let[r,o]=t;const d=e.props[r];void 0!==o&&o!==d&&I(n,r,o)}))}function I(e,t,n){"className"===t?e.className=n:"value"===t?e.value!==n&&(e.value=n):"style"===t?e.style.cssText=n:"dangerouslySetInnerHTML"===t?e.innerHTML=n.__html:t.startsWith("on")?(0,a.Oo)(e,t,n,t.endsWith("Capture")):t.startsWith("data-")||t.startsWith("aria-")||s.has(t)?e.setAttribute(t,n):i.has(t)||(e[c[t]||t]=n)}const w={render:function(e,t){if(!t)return;let n=t.getAttribute("data-teact-head-id");n||(n=(0,o.Z)(l),l[n]={children:[]},t.setAttribute("data-teact-head-id",n));const r=l[n];r.children=[f(t,r.children[0],e,r,0)]}}},4050:(e,t,n)=>{n.d(t,{CD:()=>x,Hb:()=>T,I4:()=>_,O_:()=>v,SO:()=>M,U9:()=>R,V2:()=>h,X$:()=>U,Ye:()=>Z,ZP:()=>j,Zb:()=>k,bt:()=>D,d4:()=>O,eJ:()=>B,iB:()=>m,k:()=>A,op:()=>g,sO:()=>$});var r=n(3716),o=n(9118),d=n(782),a=n(275),u=n(3592),i=n(5247);let s;!function(e){e[e.Empty=0]="Empty",e[e.Text=1]="Text",e[e.Tag=2]="Tag",e[e.Component=3]="Component"}(s||(s={}));const c=Symbol("Fragment"),l=new Set(["TeactMemoWrapper","TeactNContainer","Button","ListItem","MenuItem"]);let f;function h(e){return e.type===s.Empty}function m(e){return e.type===s.Text}function p(e){return e.type===s.Tag}function g(e){return e.type===s.Component}function v(e){return p(e)||g(e)}function y(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),o=2;o1&&void 0!==arguments[1]?arguments[1]:[];const{props:n}=e;return{componentInstance:e,type:s.Component,props:n,children:t}}function w(e,t,n){return{type:s.Tag,tag:e,props:t,children:C(n).map(E)}}function C(e){let t=e.length-1;for(;t>=0&&S(e[t]);t--);return t+17&&console.warn(`[Teact] Slow component render: ${n}, ${Math.round(t)} ms`),P[n].renderTimes.push(t),P[n].renderCount++}}catch(t){(0,u.S)(t),o=e.renderedValue}if(e.isMounted&&o===e.renderedValue)return e.$element;e.renderedValue=o;const d=E(o);return e.$element=I(e,[d]),e.$element}function A(e,t){return typeof e!=typeof t||e.type!==t.type||(m(e)&&m(t)?e.value!==t.value:p(e)&&p(t)?e.tag!==t.tag||e.props.key!==t.props.key:!(!g(e)||!g(t)||e.componentInstance.Component===t.componentInstance.Component&&e.props.key===t.props.key))}function k(e){if(g(e))(t=e.componentInstance).isMounted&&(t.hooks.memos.byCursor.forEach((e=>{e.current=void 0})),t.hooks.effects.byCursor.forEach((e=>{let{cleanup:t}=e;if("function"==typeof t)try{t()}catch(e){(0,u.S)(e)}})),t.isMounted=!1,function(e){e.hooks.effects.byCursor.forEach((e=>{e.cleanup=void 0,e.effect=void 0,e.dependencies=void 0})),e.hooks.state.byCursor.forEach((e=>{e.value=void 0,e.nextValue=void 0,e.setter=void 0})),e.hooks.memos.byCursor.forEach((e=>{e.dependencies=void 0})),e.hooks=void 0,e.$element=void 0,e.renderedValue=void 0,e.Component=void 0,e.props=void 0,e.forceUpdate=void 0,e.onUpdate=void 0}(t));else if(p(e)&&(e.target&&(0,i.lQ)(e.target),e.props.ref&&(e.props.ref.current=void 0)),e.target&&(e.target=void 0),!v(e))return;var t;e.children.forEach(k)}function T(e){return M(e),e.isMounted=!0,e.$element}function N(e){e.isMounted&&(e.hooks.state.byCursor.forEach((e=>{e.value=e.nextValue})),e.prepareForFrame=(0,o.wT)((()=>N(e))),e.forceUpdate=(0,o.mS)((()=>L(e))))}function L(e){if(!e.isMounted||!e.onUpdate)return;const t=e.$element;M(e),e.$element!==t&&e.onUpdate()}function R(e){if(g(e)){const t=e.children[0];return t?R(t):void 0}return e.target}function x(e,t){g(e)?x(e.children[0],t):e.target=t}function B(e){const{cursor:t,byCursor:n}=f.hooks.state;var d;return void 0===n[t]&&(n[t]={value:e,nextValue:e,setter:(d=f,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)((()=>N(d))),d.forceUpdate=(0,o.mS)((()=>L(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))})}),f.hooks.state.cursor++,[n[t].value,n[t].setter]}function F(e,t,n,o,d){const{cursor:a,byCursor:i}=f.hooks.effects,s=f;function c(){if(!s.isMounted)return;const{cleanup:e}=i[a];if("function"==typeof e)try{let t;if(r.eM&&(t=performance.now()),e(),r.eM){const e=performance.now()-t,n=s.name;e>7&&console.warn(`[Teact] Slow cleanup at effect cursor #${a}: ${n}, ${Math.round(e)} ms`)}}catch(e){(0,u.S)(e)}}function l(){if(!s.isMounted)return;let e;if(r.eM&&(e=performance.now()),i[a].cleanup=n(),r.eM){const t=performance.now()-e,n=s.name;t>7&&console.warn(`[Teact] Slow effect at cursor #${a}: ${n}, ${Math.round(t)} ms`)}}if(void 0!==i[a]&&o&&i[a].dependencies){if(o.some(((e,t)=>e!==i[a].dependencies[t]))){if(d){const e=o.reduce(((e,t,n)=>{const r=i[a].dependencies[n];return t!==r&&e.push(`${n}: ${r} => ${t}`),e}),[]);console.log(`[Teact] Effect "${d}" caused by dependencies.`,e.join(", "))}t(c),e(l)}}else d&&console.log(`[Teact] Effect "${d}" caused by missing dependencies.`),t(c),e(l);i[a]={effect:n,dependencies:o,cleanup:i[a]?i[a].cleanup:void 0},f.hooks.effects.cursor++}function O(e,t,n){return F(o.T2,o.D0,e,t,n)}function D(e,t,n){return F(o.R3,o.zD,e,t,n)}function Z(e,t,n){const{cursor:o,byCursor:d}=f.hooks.memos;let{current:u}=d[o]||{};return(void 0===d[o]||t.some(((e,t)=>e!==d[o].dependencies[t])))&&(r.eM&&n&&console.log(`[Teact.useMemo] ${f.name} (${n}): Update is caused by:`,d[o]?(0,a.c)(t,d[o].dependencies).join(", "):"[first render]"),u=e()),d[o]={current:u,dependencies:t},f.hooks.memos.cursor++,u}function _(e,t,n){return Z((()=>e),t,n)}function $(e){return Z((()=>({current:e})),[])}function U(e,t){return function(n){return Z((()=>y(e,n)),Object.values(n),t)}}document.addEventListener("dblclick",(()=>{console.warn("COMPONENTS",(0,d.Xo)(Object.values(P),"renderCount","desc"))}));const j={createElement:y,Fragment:c}},5116:(e,t,n)=>{n.d(t,{Iq:()=>P,Rd:()=>w,gP:()=>A,ll:()=>E});var r=n(4050),o=n(3716),d=n(5326),a=n(6926),u=n(9118),i=n(275),s=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`)}}],g={},v=new Map,y=(0,u.$6)(b);function b(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];e||!(0,l.zG)()?p.forEach((e=>e(h))):(0,u.T2)(y)}function I(e,t){"object"==typeof e&&e!==h&&(h=e,null!=t&&t.forceSyncOnIOs?b(!0):y(null==t?void 0:t.forceOnHeavyAnimation))}function w(){return h}function C(){return g}function S(e,t){m[e]||(m[e]=[],g[e]=(t,n)=>{!function(e,t,n){var r;null===(r=m[e])||void 0===r||r.forEach((e=>{const r=e(h,g,t);r&&("function"==typeof r.then?r.then((e=>{e&&I(e,n)})):I(r,n))}))}(e,t,n)}),m[e].push(t)}function E(e){p.push(e)}function P(e){const t=p.indexOf(e);-1!==t&&p.splice(t,1)}function M(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:()=>({});return t=>function n(o){n.DEBUG_contentComponentName=t.name;const[u]=(0,r.eJ)((0,a.Z)(v)),s=(0,d.Z)();(0,r.d4)((()=>()=>{v.delete(u)}),[u]);let l=v.get(u);if(l||(l={mapStateToProps:e,ownProps:o,areMappedPropsChanged:!1,forceUpdate:s,DEBUG_updates:0,DEBUG_componentName:t.name},v.set(u,l)),l.areMappedPropsChanged&&(l.areMappedPropsChanged=!1),!l.mappedProps||!(0,i.Z)(l.ownProps,o)){l.ownProps=o;try{l.mappedProps=e(h,o)}catch(e){(0,c.S)(e)}}return r.ZP.createElement(t,f({},l.mappedProps,o))}}function A(){return{getGlobal:w,setGlobal:I,getActions:C,addActionHandler:S,withGlobal:M}}o.eM&&(window.getGlobal=w,document.addEventListener("dblclick",(()=>{console.warn("GLOBAL CONTAINERS",(0,s.Xo)(Array.from(v.values()).map((e=>{let{DEBUG_componentName:t,DEBUG_updates:n}=e;return{DEBUG_componentName:t,DEBUG_updates:n}})),"DEBUG_updates","desc"))})))},3681:(e,t,n)=>{n.d(t,{Z:()=>a,l:()=>d});const r=/\uFE0F/g,o=String.fromCharCode(8205);function d(e){return e.indexOf(o)<0?e.replace(r,""):e}const a=/(?:\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},1713:(e,t,n)=>{let r,o,d,a,u,i,s,c,l,f,h,m,p,g;n.d(t,{Cr:()=>c,KB:()=>g,MT:()=>d,Nh:()=>l,Uq:()=>r,WB:()=>m,bZ:()=>s,du:()=>a,fo:()=>o,mp:()=>v,nJ:()=>u,qt:()=>i,rN:()=>f,u1:()=>y,vi:()=>p,wv:()=>h}),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",e[e.QuickReaction=50]="QuickReaction"}(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"}(a||(a={})),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"}(u||(u={})),function(e){e[e.ChatInfo=0]="ChatInfo",e[e.Search=1]="Search",e[e.Management=2]="Management",e[e.Statistics=3]="Statistics",e[e.StickerSearch=4]="StickerSearch",e[e.GifSearch=5]="GifSearch",e[e.PollResults=6]="PollResults",e[e.AddingMembers=7]="AddingMembers"}(i||(i={})),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"}(s||(s={})),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",e[e.ConfirmPayment=4]="ConfirmPayment"}(g||(g={}));const v="UPLOADING_WALLPAPER_SLUG";let y;!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.ChannelRemovedUsers=7]="ChannelRemovedUsers",e[e.GroupUserPermissionsCreate=8]="GroupUserPermissionsCreate",e[e.GroupUserPermissions=9]="GroupUserPermissions",e[e.ChatAdministrators=10]="ChatAdministrators",e[e.GroupRecentActions=11]="GroupRecentActions",e[e.ChatAdminRights=12]="ChatAdminRights",e[e.ChatNewAdminRights=13]="ChatNewAdminRights",e[e.GroupMembers=14]="GroupMembers",e[e.GroupAddAdmins=15]="GroupAddAdmins",e[e.Invites=16]="Invites",e[e.EditInvite=17]="EditInvite",e[e.Reactions=18]="Reactions",e[e.InviteInfo=19]="InviteInfo",e[e.JoinRequests=20]="JoinRequests"}(y||(y={}))},9933:(e,t,n)=>{n.d(t,{M8:()=>u,cK:()=>d,jt:()=>a,vr:()=>i});var r=n(9118);let o;function d(e,t){t||(o&&!o.isCancelled&&(o.isCancelled=!0),o=t={isCancelled:!1}),!t.isCancelled&&e()&&(0,r.T2)((()=>{d(e,t)}))}function a(e){e()&&(0,r.T2)((()=>{a(e)}))}const u={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 i(e){let{timing:t=u.linear,onUpdate:n,duration:r,onEnd:o,from:d,to:i}=e;const s=Date.now();let c=!1;return a((()=>{if(c)return!1;let e=(Date.now()-s)/r;e>1&&(e=1);const a=t(e);if("number"==typeof d&&"number"==typeof i)n(d+(i-d)*a);else if(Array.isArray(d)&&Array.isArray(i)){const e=d.map(((e,t)=>e+(i[t]-e)*a));n(e)}return 1===e&&o&&o(),e<1})),()=>{c=!0,o&&o()}}},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)=>{function r(){for(var e=arguments.length,t=new Array(e),n=0;n1?r-1:0),d=1;d(t&&(Array.isArray(t)?e.push(...t):e.push(`${n}--${t}`)),e)),[n]).join(" ")}}n.d(t,{Z:()=>r,y:()=>o})},9524:(e,t,n)=>{n.d(t,{Type:()=>o,clear:()=>u,fetch:()=>d,save:()=>a});const r=self.caches;let o;async function d(e,t,n){let d=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(r)try{const a=new Request(t.replace(/:/g,"_")),u=await r.open(e),i=await u.match(a);if(!i)return;const s=i.headers.get("Content-Type");switch(n){case o.Text:return await i.text();case o.Blob:{if(t.startsWith("avatar")&&s&&s.startsWith("text"))return;const e=await i.blob(),n=!e.type||!d&&e.type.includes("html");let r=e.type||s;return n&&r?(d||(r=r.replace(/html/gi,"")),new Blob([e],{type:r})):e}case o.Json:return await i.json();default:return}}catch(e){return void console.warn(e)}}async function a(e,t,n){if(r)try{const o="string"==typeof n||n instanceof Blob?n:JSON.stringify(n),d=new Request(t.replace(/:/g,"_")),a=new Response(o),u=await r.open(e);return await u.put(d,a)}catch(e){return void console.warn(e)}}async function u(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={}))},6063:(e,t,n)=>{function r(){const e=[];function t(t){const n=e.indexOf(t);-1!==n&&e.splice(n,1)}return{runCallbacks:function(){for(var t=arguments.length,n=new Array(t),r=0;r{e(...n)}))},addCallback:function(n){return e.push(n),()=>{t(n)}},removeCallback:t,hasCallbacks:function(){return Boolean(e.length)}}}n.d(t,{_:()=>r})},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 a()||document.addEventListener("keydown",u,!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)}})),a()||document.removeEventListener("keydown",u,!1)}(e)}}function a(){return Object.values(o).some((e=>Boolean(e.length)))}function u(e){const t=r[e.key];if(!t)return;const{length:n}=o[t];n&&(e.stopPropagation(),(0,o[t][n-1])(e))}},4319:(e,t,n)=>{n.d(t,{TE:()=>a,VP:()=>u,yl:()=>o});var r=n(3716);const o=window.navigator.clipboard&&window.ClipboardItem,d=document.createElement("textarea");d.setAttribute("readonly",""),d.tabIndex=-1,d.className="visually-hidden";const a=e=>{d.value=e,document.body.appendChild(d);const t=document.getSelection();if(t){const e=t.rangeCount>0&&t.getRangeAt(0);d.select(),document.execCommand("copy"),e&&(t.removeAllRanges(),t.addRange(e))}document.body.removeChild(d)},u=e=>{if(!e)return;const t=document.createElement("canvas"),n=t.getContext("2d"),r=new Image;r.onload=e=>{if(n&&e.currentTarget){const r=e.currentTarget;t.width=r.width,t.height=r.height,n.drawImage(r,0,0,r.width,r.height),t.toBlob(i,"image/png",1)}},r.src=e};async function i(e){if(e&&o)try{var t,n;await(null===(t=(n=window.navigator.clipboard).write)||void 0===t?void 0:t.call(n,[new ClipboardItem({[e.type]:e})]))}catch(e){r.eM&&console.error(e)}}},790:(e,t,n)=>{n.d(t,{$Y:()=>s,D:()=>v,IS:()=>N,SA:()=>A,Tu:()=>p,VX:()=>m,ZK:()=>C,_F:()=>c,dJ:()=>b,j1:()=>I,k9:()=>S,kj:()=>l,mB:()=>y,mr:()=>h,np:()=>g,rM:()=>E,xH:()=>M,xR:()=>u,xk:()=>T,zk:()=>i});var r=n(5155);const o=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],d=["January","February","March","April","May","June","July","August","September","October","November","December"],a=d.map((e=>e.toLowerCase())),u=864e5;function i(e){return c(new Date)===c(e)}function s(e){const t=new Date(e);return t.setHours(0,0,0,0),t}function c(e){return s(e).getTime()}function l(e){const t=new Date(1e3*e);return`${t.getFullYear()}-${t.getMonth()}`}function f(e){return`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`}function h(e,t){const n="number"==typeof t?new Date(t):t,r=e.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 m(e,t){const n="number"==typeof t?new Date(t):t,r=s(new Date);if(n>=r)return h(e,n);const d=new Date(r);if(d.setDate(r.getDate()-7),n>=d)return e(`Weekday.Short${o[n.getDay()]}`);const a=n.getFullYear()!==r.getFullYear(),u=e(a?"formatDateScheduleYear":"formatDateSchedule")||(a?"d MMM yyyy":"d MMM");return w(e,n,u)}function p(e,t){const n="number"==typeof t?new Date(t):t,r=e("formatterYearMax")||"dd.MM.yyyy";return w(e,n,r)}function g(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const r=e(n?"formatterMonthYear2":"formatterMonthYear")||"MMM yyyy";return w(e,t,r)}function v(e,t){const n=Math.floor(t/u);return t<0?0:n<1?S(t/1e3):n<7?e("Days",n):n<30?e("Weeks",Math.floor(n/7)):n<365?e("Months",Math.floor(n/30)):e("Years",Math.floor(n/365))}function y(e,t){return t<6e4?Math.ceil(t/1e3):t<36e5?Math.ceil(t/6e4):t2&&void 0!==arguments[2]?arguments[2]:t;const r=t-n;return r<60?e("LiveLocationUpdated.JustNow"):r<3600?e("LiveLocationUpdated.MinutesAgo",Math.floor(r/60)):e("LiveLocationUpdated.TodayAt",h(e,n))}function I(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],d=arguments.length>4?arguments[4]:void 0;const a="number"==typeof t?new Date(t):t,u=s(new Date);if(!r){if(f(a)===f(u))return(d||!n?R:L)(e("Weekday.Today"));const t=new Date(u);if(t.setDate(u.getDate()-1),f(a)===f(t))return(d||!n?R:L)(e("Weekday.Yesterday"));const r=new Date(u),i=new Date(u);if(r.setDate(u.getDate()-7),i.setDate(u.getDate()+7),a>=r&&a<=i){const t=o[a.getDay()];return(d||!n?R:L)(e(n?`Weekday.Short${t}`:`Weekday.${t}`))}}const i=a.getFullYear()!==u.getFullYear(),c=n?i?"formatDateScheduleYear":"formatDateSchedule":i?"chatFullDate":"chatDate",l=e(c)||"d MMMM yyyy";return(d||!n?R:L)(w(e,a,l))}function w(e,t,n){const r=t.getDate(),o=t.getMonth();return n.replace("LLLL",e(d[o])).replace("MMMM",e(`Month.Gen${d[o]}`)).replace("MMM",e(`Month.Short${d[o]}`)).replace("MM",String(o+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 C(e,t,n){const r="number"==typeof t?new Date(t):t;return`${I(e,r,!0,void 0,n)}, ${h(e,r)}`}function S(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,a=t?Math.floor(t%3600/60):0;let u="";return n>0||d>0?(u+=`${String(n).padStart(2,"0")}:`,u+=`${String(r).padStart(2,"0")}:`):u+=a>=10?`${String(r).padStart(2,"0")}:`:`${String(r)}:`,u+=String(o).padStart(2,"0"),u}function E(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")}`}const P=(0,r.Z)(((e,t)=>new Date(e).toLocaleString(t,{year:"numeric",month:"short",day:"numeric"})));function M(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"en-US";const n="number"==typeof e?new Date(e):e,r=c(n);return P(r,t)}function A(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"en-US";const n="number"==typeof e?new Date(e):e;return n.toLocaleString(t,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})}function k(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:2021;if(t>11||e>31)return!1;const r=new Date(n,t,e);return!Number.isNaN(r.getTime())&&r.getDate()===e}function T(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";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||!k(t,n-1,r||void 0)?void 0:`${r?`${r}-`:""}${String(n).padStart(2,"0")}-${String(t).padStart(2,"0")}`}const o=e.split(" "),d=t?o[0]:o[1],u=(t?o[1]:o[0]).toLowerCase(),i=a.findIndex((e=>e.startsWith(u)));return-1!==i&&k(Number(d),i)?`${String(i+1).padStart(2,"0")}-${String(d).padStart(2,"0")}`:void 0}function N(e){return e+u/1e3}function L(e){return`${e[0].toLowerCase()}${e.slice(1)}`}function R(e){return`${e[0].toUpperCase()}${e.slice(1)}`}},4284:(e,t,n)=>{n.d(t,{NM:()=>s,U_:()=>i,Wg:()=>c,g6:()=>u});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 a(e){const t=e.split("-").map((e=>parseInt(e,16)));return String.fromCodePoint(...t)}function u(e){if(!e.match(r.Z))return e;for(const[t,n]of d)e=e.replace(t,n);return e}function i(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 s(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:()=>x,wZ:()=>p,gk:()=>F,vX:()=>M,FW:()=>O,op:()=>C,cj:()=>m,jm:()=>h,pA:()=>L,m5:()=>P,I_:()=>E,fl:()=>v,t0:()=>A,s$:()=>g,i4:()=>D,Mc:()=>S,wB:()=>b,p7:()=>I,$b:()=>y,mh:()=>w,Hh:()=>R,s0:()=>T,aZ:()=>B,gZ:()=>Z,Lt:()=>f,vn:()=>s,on:()=>d});var r=n(3716);let o;function d(){return Boolean(o)}var a,u;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 i=null!==(a=(u=window).matchMedia)&&void 0!==a&&a.call(u,"(prefers-color-scheme: dark)").matches?"dark":"light";function s(){return i}function c(e){i=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),v=window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone||document.referrer.includes("android-app://"),y=window.matchMedia("(pointer: coarse)").matches,b=window.innerWidth<=r.l3||window.innerWidth<=r.u_&&window.innerHeight<=r.rO,I=!b&&window.innerWidth<=r.ks,w=Boolean(window.navigator.mediaDevices&&"getUserMedia"in window.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=!0;L&&r.wG.add(r.Ng);const R=Boolean(N.canPlayType('video/webm; codecs="vp9"').replace("no",""))&&!(h&&g),x=window.devicePixelRatio||1,B=!0,F=!r.Cg&&(CSS.supports("backdrop-filter: blur()")||CSS.supports("-webkit-backdrop-filter: blur()")),O=!y,D=!h&&!m&&!p,Z=D?300:750},1394:(e,t,n)=>{n.d(t,{A9:()=>d,YJ:()=>a,ao:()=>h,dc:()=>f,gm:()=>l,hl:()=>u,jj:()=>s,pt:()=>i,ud:()=>c});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 a(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 u(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}function i(e){return new Promise(((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=n,r.src=e}))}function s(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 s(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 u(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}})},6974:(e,t,n)=>{n.d(t,{M2:()=>P,O6:()=>A,S1:()=>b,Yz:()=>C,aE:()=>w,gO:()=>I,r_:()=>M,wC:()=>S,xW:()=>E});var r=n(5116),o=n(3555),d=n(3716),a=n(1192),u=n(5806),i=n(9118),s=n(782),c=n(275),l=n(6063);const f=R();let h=f.prevGlobal,m=f.prepared,p=f.results,g=f.callbacks;const v=(0,i.P2)((()=>{(0,i.Q8)((()=>{k((0,o.Rd)())}))}),500);let y=!1;function b(){y=!0,(0,r.ll)(v),(0,o.iw)("reset",x),k((0,o.Rd)())}function I(e){return y||b(),p.orderedIdsByFolderId[e]}function w(e){return y||b(),p.pinnedCountByFolderId[e]||0}function C(){return y||b(),p.chatsCountByFolderId}function S(){return y||b(),p.unreadCountersByFolderId}function E(){var e;return(null===(e=S()[d.Nf])||void 0===e?void 0:e.notificationsCount)||0}function P(e,t){return g.orderedIdsByFolderId[e]||(g.orderedIdsByFolderId[e]=(0,l._)()),g.orderedIdsByFolderId[e].addCallback(t)}function M(e){return g.chatsCountByFolderId.addCallback(e)}function A(e){return g.unreadCountersByFolderId.addCallback(e)}function k(e){let t;d.eM&&(t=performance.now());const n=Boolean(e.chats.listIds.active&&T(d.Nf,e.chats.listIds.active,e.chats.orderedPinnedIds.active)),r=Boolean(e.chats.listIds.archived&&T(d.WS,e.chats.listIds.archived,e.chats.orderedPinnedIds.archived)),o=e.chats.isFullyLoaded.active!==h.isAllFolderFullyLoaded,i=e.chats.isFullyLoaded.archived!==h.isArchivedFolderFullyLoaded,l=e.chatFolders.byId!==h.foldersById,f=e.chats.byId!==h.chatsById,g=e.users.byId!==h.usersById,v=(0,a.dZ)(e)!==h.notifySettings,y=(0,a.NJ)(e)!==h.notifyExceptions;let b=[];if((o||i)&&(b=b.concat(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=[];t&&n.push(d.WS);const r=e.chats.isFullyLoaded.active,o=e.chats.isFullyLoaded.archived;if(r&&o){const e=Object.keys(m.folderSummariesById).filter((e=>!p.orderedIdsByFolderId[e])).map(Number);n=n.concat(e)}return h.isAllFolderFullyLoaded=r,h.isArchivedFolderFullyLoaded=o,n}(e,i))),!(n||r||l||f||g||v||y))return void(b.length&&L(b));const I=h.allFolderListIds,w=h.archivedFolderListIds;if(function(e,t,n,r){const o=[];if(t){const t=e.chats.listIds.active,n=e.chats.orderedPinnedIds.active;m.folderSummariesById[d.Nf]=N(d.Nf,t,n),h.allFolderListIds=t,h.allFolderPinnedIds=n,o.push(d.Nf)}if(n){const t=e.chats.listIds.archived,n=e.chats.orderedPinnedIds.archived;m.folderSummariesById[d.WS]=N(d.WS,t,n),h.archivedFolderListIds=t,h.archivedFolderPinnedIds=n,o.push(d.WS)}if(r){const t=e.chatFolders.byId;Object.values(t).forEach((e=>{e!==h.foldersById[e.id]&&(m.folderSummariesById[e.id]=function(e){return{...e,orderedPinnedIds:e.pinnedChatIds,excludedChatIds:e.excludedChatIds?new Set(e.excludedChatIds):void 0,includedChatIds:e.excludedChatIds?new Set(e.includedChatIds):void 0,pinnedChatIds:e.excludedChatIds?new Set(e.pinnedChatIds):void 0}}(e),o.push(e.id))})),h.foldersById=t}}(e,n,r,l),b=b.concat(function(e,t,n,r,o,i){const l=e.chats.byId,f=e.users.byId,g=(0,a.dZ)(e),v=(0,a.NJ)(e),y=Object.values(m.folderSummariesById),b=new Set,I=e.chats.listIds.active,w=e.chats.listIds.archived;let C=[...I||[],...w||[]];return I===o&&w===i||(C=(0,s.Tw)(C.concat(o||[],i||[]))),C.forEach((e=>{const o=l[e];if(!t&&!n&&!r&&o===h.chatsById[e]&&f[e]===h.usersById[e])return;let a;if(o){const n=m.chatSummariesById.get(e),r=function(e,t,n,r){const{id:o,type:a,lastMessage:i,isRestricted:s,isNotJoined:c,folderId:l,unreadCount:f,unreadMentionsCount:h,hasUnreadMark:m,joinDate:p,draftDate:g}=e,v="chatTypePrivate"===a&&r;return{id:o,type:a,isListed:Boolean(i&&!s&&!c),isArchived:l===d.WS,isMuted:(0,u.i4)(e,t,n),isUnread:Boolean(f||h||m),unreadCount:f,unreadMentionsCount:h,order:Math.max(p||0,g||0,(null==i?void 0:i.date)||0),isUserBot:v?"userTypeBot"===v.type:void 0,isUserContact:v?v.isContact:void 0}}(o,g,v,f[e]);if(!t&&n&&(0,c.Z)(r,n))return;m.chatSummariesById.set(e,r),a=function(e,t){return t.reduce(((t,n)=>(function(e,t){var n,r,o;if(!e.isListed)return!1;const{id:a,type:u}=e;if(t.listIds)return!(e.isArchived&&t.id===d.Nf||!e.isArchived&&t.id===d.WS)&&t.listIds.has(a);if(null!==(n=t.excludedChatIds)&&void 0!==n&&n.has(a))return!1;if(null!==(r=t.includedChatIds)&&void 0!==r&&r.has(a))return!0;if(null!==(o=t.pinnedChatIds)&&void 0!==o&&o.has(a))return!0;if(t.excludeArchived&&e.isArchived)return!1;if(t.excludeRead&&!e.isUnread)return!1;if(t.excludeMuted&&e.isMuted&&!e.unreadMentionsCount)return!1;if("chatTypePrivate"===u)if(e.isUserBot){if(t.bots)return!0}else{if(t.contacts&&e.isUserContact)return!0;if(t.nonContacts&&!e.isUserContact)return!0}else{if("chatTypeChannel"===u)return Boolean(t.channels);if("chatTypeBasicGroup"===u||"chatTypeSuperGroup"===u)return Boolean(t.groups)}return!1}(e,n)&&t.push(n.id),t)),[]).sort()}(r,y),a.forEach((e=>{b.add(e)}))}else m.chatSummariesById.delete(e),a=[];const i=m.folderIdsByChatId[e]||[];if((0,s.et)(a,i))return;const I=function(e,t,n){const r=new Set(t),o=new Set(n),d=[];return(0,s.Tw)([...t,...n]).forEach((t=>{let n=p.orderedIdsByFolderId[t];r.has(t)&&!o.has(t)?(m.chatIdsByFolderId[t].delete(e),d.push(t),n&&(n=n.filter((t=>t!==e)),m.isOrderedListJustPatched[t]=!0)):!r.has(t)&&o.has(t)&&(m.chatIdsByFolderId[t]||(m.chatIdsByFolderId[t]=new Set),m.chatIdsByFolderId[t].add(e),n&&(n.push(e),m.isOrderedListJustPatched[t]=!0)),p.orderedIdsByFolderId[t]=n})),m.folderIdsByChatId[e]=n,d}(e,i,a);I.forEach((e=>{b.add(e)}))})),h.chatsById=l,h.usersById=f,h.notifySettings=g,h.notifyExceptions=v,Array.from(b)}(e,l||n||r,v,y,I,w)),L((0,s.Tw)(b)),d.eM){const e=performance.now()-t;e>6&&console.warn(`Slow \`updateFolderManager\`: ${Math.round(e)} ms`)}}function T(e,t,n){const r=e===d.Nf?h.allFolderListIds:h.archivedFolderListIds,o=e===d.Nf?h.allFolderPinnedIds:h.archivedFolderPinnedIds;return r!==t||o!==n}function N(e,t,n){return{id:e,listIds:new Set(t),orderedPinnedIds:n,pinnedChatIds:new Set(n)}}function L(e){let t=!1,n=!1;if(Array.from(e).forEach((e=>{const{pinnedCount:r,orderedIds:o}=function(e){const t=m.folderSummariesById[e];if(!t)return{};const{orderedPinnedIds:n,pinnedChatIds:r}=t,{chatSummariesById:o,chatIdsByFolderId:{[e]:d}}=m,{orderedIdsByFolderId:{[e]:a}}=p,u=d?null==n?void 0:n.filter((e=>d.has(e))):n,i=a||d&&Array.from(d)||[],s=(r?i.filter((e=>!r.has(e))):i).sort(((e,t)=>o.get(t).order-o.get(e).order));return{pinnedCount:(null==u?void 0:u.length)||0,orderedIds:[...u||[],...s]}}(e);if(!o)return;const d=p.orderedIdsByFolderId[e],a=p.pinnedCountByFolderId[e];var u;d&&void 0!==a&&a===r&&!m.isOrderedListJustPatched[e]&&(0,s.et)(o,d)||(m.isOrderedListJustPatched[e]=!1,p.orderedIdsByFolderId[e]=o,p.pinnedCountByFolderId[e]=r,null===(u=g.orderedIdsByFolderId[e])||void 0===u||u.runCallbacks(o));const i=p.chatsCountByFolderId[e],l=o.length;n||(n=i!==l),p.chatsCountByFolderId[e]=l;const f=p.unreadCountersByFolderId[e],h=function(e){const{chatSummariesById:t}=m,{orderedIdsByFolderId:{[e]:n}}=p;return n.reduce(((e,n)=>{const r=t.get(n);return r?(r.isUnread&&(e.chatsCount++,r.unreadMentionsCount&&(e.notificationsCount+=r.unreadMentionsCount),r.isMuted||(r.unreadCount?e.notificationsCount+=r.unreadCount:r.unreadMentionsCount||(e.notificationsCount+=1))),e):e}),{chatsCount:0,notificationsCount:0})}(e);t||(t=!f||!(0,c.Z)(h,f)),p.unreadCountersByFolderId[e]=h})),n){const e={...p.chatsCountByFolderId};p.chatsCountByFolderId=e,g.chatsCountByFolderId.runCallbacks(e)}if(t){const e={...p.unreadCountersByFolderId};p.unreadCountersByFolderId=e,g.unreadCountersByFolderId.runCallbacks(e)}}function R(){return{prevGlobal:{foldersById:{},chatsById:{},usersById:{},notifySettings:{},notifyExceptions:{}},prepared:{folderSummariesById:{},chatSummariesById:new Map,folderIdsByChatId:{},chatIdsByFolderId:{},isOrderedListJustPatched:{}},results:{orderedIdsByFolderId:{},pinnedCountByFolderId:{},chatsCountByFolderId:{},unreadCountersByFolderId:{}},callbacks:{orderedIdsByFolderId:{},chatsCountByFolderId:(0,l._)(),unreadCountersByFolderId:(0,l._)()}}}function x(){const e=R();h=e.prevGlobal,m=e.prepared,p=e.results,g=e.callbacks}},9937:(e,t,n)=>{function r(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"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,{J_:()=>a,ZP:()=>d});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. Streaming media may not be supported. Try reloading 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",BOT_PRECHECKOUT_TIMEOUT:"The request for payment has expired"},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 a(e){return o[e.message]}},3592:(e,t,n)=>{n.d(t,{S:()=>d}),n(3716);var r=n(9118);function o(e){e instanceof ErrorEvent&&"ResizeObserver loop limit exceeded"===e.message||(e.preventDefault(),d(e instanceof ErrorEvent?e.error||e.message: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 a(e,t){return t.reduce(((t,n)=>(e[n]&&(t[n]=e[n]),t)),{})}function u(e,t){const n=new Set(t.map(String));return d(e,Object.keys(e).filter((e=>!n.has(e))))}function i(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"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],[a,u]=t,i="asc"===o,s="asc"===d;return e.sort(((e,t)=>r(e,t,a,i)||r(e,t,u,s)))}const o="asc"===n;return e.sort(((e,n)=>r(e,n,t,o)))}function s(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 v(e,t){let n=e.length;for(;n--;)if(t(e[n],n,e))return e[n]}n.d(t,{CE:()=>u,Q8:()=>o,Tw:()=>c,Vl:()=>p,Xh:()=>g,Xo:()=>i,YE:()=>h,dF:()=>v,eL:()=>m,ee:()=>r,ei:()=>d,et:()=>f,oA:()=>l,q0:()=>a,xH:()=>s})},711:(e,t,n)=>{n.d(t,{Pn:()=>w,i0:()=>I,ll:()=>p,m0:()=>C,qf:()=>S});var r=n(3555),o=n(3716),d=n(9524),a=n(1226),u=n(6063),i=n(2155);const s=/%\d?\$?[sdf@]/g,c=["value","zeroValue","oneValue","twoValue","fewValue","manyValue","otherValue"],l={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},f=new Map;let h,m;const{addCallback:p,removeCallback:g,runCallbacks:v}=(0,u._)();let y,b;const I=(e,t,n)=>{var r,o;if(void 0!==t){const r=Array.isArray(t)?JSON.stringify(t):t,o=f.get(`${e}_${r}_${n}`);if(o)return o}if(!h&&!m)return e;const d=(null===(r=h)||void 0===r?void 0:r[e])||(null===(o=m)||void 0===o?void 0:o[e]);return d?M(d,e,t,n):(m||E(),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,a.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)),M(n,t)}async function C(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(h&&e===y)return void(t&&t());let a=await d.fetch(o.ee,e,d.Type.Json);if(!a&&(n&&await E(),a=await P(e),!a))return;f.clear(),y=e,h=a,document.documentElement.lang=e;const{languages:u,timeFormat:i}=(0,r.Rd)().settings.byKey,s=null==u?void 0:u.find((t=>t.langCode===e));I.isRtl=Boolean(null==s?void 0:s.rtl),I.code=e,I.timeFormat=i,t&&t(),v()}function S(e){e&&e===b||(b=e,I.timeFormat=e,v())}async function E(){m||(m=(await n.e(915).then(n.bind(n,1915))).default,v())}async function P(e){const t=await(0,a.t9)("fetchLangPack",{sourceLangPacks:o.Bg,langCode:e});if(t)return await d.save(o.ee,e,t.langPack),t.langPack}function M(e,t,n,r){const d=e?e["number"==typeof n?function(e){const t=y||o.sR,n=l[t]?l[t](e):0;return c[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,i.kh)(n):n),o=Array.isArray(n)?JSON.stringify(n):n;return f.set(`${t}_${o}_${r}`,e),e}return d}},647:(e,t,n)=>{n.d(t,{cC:()=>b,he:()=>v,UV:()=>y,Iq:()=>I});var r=n(6137),o=n(3716),d=n(1226),a=n(9524),u=n(1394),i=n(7361);const s=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((e=>{let{buffer:t}=e;return t})))},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:s}),o.postMessage({command:"init",decoderSampleRate:s,outputBufferSampleRate:s}),o.postMessage({command:"decode",pages:r},[r.buffer])}))}var l=n(862);const f={[r.IU.BlobUrl]:a.Type.Blob,[r.IU.Lottie]:a.Type.Blob,[r.IU.Progressive]:void 0,[r.IU.Stream]:void 0},h=new Map,m=new Map,p=new Map,g=new Map;function v(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],d=arguments.length>3?arguments[3]:void 0,a=arguments.length>4?arguments[4]:void 0;if(t===r.IU.Progressive)return i.I_?w(e):v(e,r.IU.BlobUrl,n,d,a);if(!m.has(e)){const r=C(e,t,n).catch((e=>{o.eM&&console.warn(e)})).finally((()=>{m.delete(e),p.delete(e),g.delete(e)}));m.set(e,r)}if(d&&a){let t=p.get(e);t||(t=new Map,p.set(e,t)),t.set(a,d)}return m.get(e)}function y(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 I(e,t){const n=p.get(e);n&&n.delete(t)}function w(e){const t=`./progressive/${e}`;return h.set(e,t),Promise.resolve(t)}async function C(e,t,n){if(!o.Cy){const r=e.startsWith("avatar")?o.SG:o.lW,d=await a.fetch(r,e,f[t],n);if(d){let t=d;if("audio/ogg"!==d.type||i.m5||(t=await c(t)),"image/webp"===d.type&&!(0,i.on)()&&t){const n=await(0,l._y)(e,t);n&&(t=n)}const n=E(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"),a=S(e,n,r);g.set(e,a),(0,d.t9)("downloadMedia",{url:e,mediaFormat:t},a)})),h.set(e,r),r}const s=S(e);g.set(e,s);const m=await(0,d.t9)("downloadMedia",{url:e,mediaFormat:t,isHtmlAllowed:n},s);if(!m)throw new Error(`Failed to fetch media ${e}`);let{prepared:p,mimeType:v}=m;if("audio/ogg"===v&&!i.m5){const e=await(0,u.gm)(p);URL.revokeObjectURL(p);const t=await c(e);p=E(t),v=t.type}if("image/webp"===v&&!(0,i.on)()){const t=await(0,u.gm)(p);URL.revokeObjectURL(p);const n=await(0,l._y)(e,t);n&&(p=E(n))}return h.set(e,p),p}function S(e,t,n){const r=(o,d)=>{var a;null===(a=p.get(e))||void 0===a||a.forEach((e=>{e(o),e.isCanceled&&(r.isCanceled=!0)})),1===o&&(null==t||t.endOfStream()),d&&(null==n||n.appendBuffer(d))};return r}function E(e){return e instanceof Blob?URL.createObjectURL(e):e}i.I_&&navigator.serviceWorker.addEventListener("message",(async e=>{const{type:t,messageId:n,params:o}=e.data;if("requestPart"!==t)return;const a=await(0,d.t9)("downloadMedia",{mediaFormat:r.IU.Progressive,...o});if(!a)return;const{arrayBuffer:u,mimeType:i,fullSize:s}=a;navigator.serviceWorker.controller.postMessage({type:"partResponse",messageId:n,result:{arrayBuffer:u,mimeType:i,fullSize:s}},[u])}))},735:(e,t,n)=>{n.d(t,{D:()=>r});const r=[]},9203:(e,t,n)=>{n.d(t,{$y:()=>c,Qt:()=>f,gl:()=>d,o5:()=>l});var r=n(3716),o=n(6063);let d;!function(e){e[e.Auth=0]="Auth",e[e.Main=1]="Main",e[e.Extra=2]="Extra",e[e.Calls=3]="Calls"}(d||(d={}));const a={},u={},{addCallback:i,runCallbacks:s}=(0,o._)();async function c(e,t){if(!a[e]){switch(e){case d.Auth:a[d.Auth]=n.e(133).then(n.bind(n,1133));break;case d.Main:r.eM&&console.log(">>> START LOAD MAIN BUNDLE"),a[d.Main]=Promise.all([n.e(888),n.e(13),n.e(970),n.e(616)]).then(n.bind(n,5616));break;case d.Extra:a[d.Extra]=Promise.all([n.e(888),n.e(13),n.e(395)]).then(n.bind(n,1395));break;case d.Calls:a[d.Calls]=Promise.all([n.e(888),n.e(970),n.e(654)]).then(n.bind(n,7526))}a[e].then(s)}const o=await a[e];return u[e]||(u[e]=o),l(e,t)}function l(e,t){const n=u[e];if(n)return n[t]}const f=i},8406:(e,t,n)=>{n.d(t,{KC:()=>A,Ld:()=>E,Nz:()=>b,Vr:()=>M,q3:()=>y,r1:()=>C,rh:()=>P});var r=n(1226),o=n(6137),d=n(8005),a=n(3716),u=n(3555),i=n(5806),s=n(5406),c=n(1192),l=n(7361),f=n(711),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!!l.Mc&&("showNotification"in ServiceWorkerRegistration.prototype?"denied"===Notification.permission?(a.eM&&console.warn("[PUSH] The user has blocked push notifications."),!1):"PushManager"in window||(a.eM&&console.warn("[PUSH] Push messaging isn't supported."),!1):(a.eM&&console.warn("[PUSH] Push notifications aren't supported."),!1))}const v=new Set;async function y(e,t){if(void 0!==e&&v.has(e))return;const{notificationSoundVolume:n}=(0,c.dZ)((0,u.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",(()=>{v.add(e)}),{once:!0}),setTimeout((()=>{v.delete(e)}),3e3));try{await o.play()}catch(e){a.eM&&console.warn("[PUSH] Unable to play notification sound")}}const b=(0,m.Ds)(y,1e3,!0,!1);async function I(){"Notification"in window&&(["granted","denied"].includes(Notification.permission)||await Notification.requestPermission())}async function w(e){const t=(0,u.Rd)(),n=(0,u.Sv)();if(e)try{const t=p(e);return await(0,r.t9)("unregisterDevice",t),await e.unsubscribe(),void n.deleteDeviceToken()}catch(e){a.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 w(t)}let S=!1;async function E(){if(!g())return void await I();const e=await navigator.serviceWorker.ready;let t=await e.pushManager.getSubscription();if(function(e){const t=(0,u.Rd)();return!t.push||!e||p(e)!==t.push.deviceToken||Date.now()-t.push.subscribedAt>432e5}(t)){await w(t);try{t=await e.pushManager.subscribe({userVisibleOnly:!0});const n=p(t);a.eM&&console.log("[PUSH] Received push subscription: ",n),await(0,r.t9)("registerDevice",n),(0,u.Sv)().setDeviceToken(n)}catch(e){"denied"===Notification.permission?a.eM&&console.warn("[PUSH] The user has blocked push notifications."):a.eM&&(console.log("[PUSH] Unable to subscribe to push.",e),e.code===DOMException.ABORT_ERR&&await I())}}}async function P(e){let{chat:t,message:n,isReaction:m=!1}=e;const{hasWebNotifications:p}=await async function(){if(S)return(0,c.dZ)((0,u.Rd)());const[e,t]=await Promise.all([(0,r.t9)("fetchNotificationSettings",{serverTimeOffset:(0,u.Rd)().serverTimeOffset}),(0,r.t9)("fetchNotificationExceptions",{serverTimeOffset:(0,u.Rd)().serverTimeOffset})]);if(!e)return(0,c.dZ)((0,u.Rd)());let n=(0,s.BI)((0,u.Rd)(),e);return t&&(n=(0,s.aJ)(n,t)),(0,u.R3)(n),S=!0,(0,c.dZ)(n)}();if(!function(e){if(!S)return!1;const t=(0,u.Rd)();if((0,i.i4)(e,(0,c.dZ)(t),(0,c.NJ)(t))||e.isNotJoined||!e.isListed)return!1;if(l.$b){const{chatId:n,type:r}=(0,c.Bt)(t)||{};return!(n===e.id&&"thread"===r)}return!document.hasFocus()}(t))return;const v="Notification"in window?"denied"!==Notification.permission||(a.eM&&console.warn("[PUSH] The user has blocked push notifications."),!1):(a.eM&&console.warn("[PUSH] This browser does not support desktop notification"),!1);if(!p||!v){if(m)return;return void b(String(n.id)||t.id)}if(!v)return;if(!n.id)return;const y=(0,i.dT)(n),I=await async function(e){const t=(0,i.RT)(e);if(!t)return;let n=h.UV(t);return n||(await h.he(t,o.IU.BlobUrl),n=h.UV(t)),n}(t),{title:w,body:C}=function(e,t,n){const r=(0,u.Rd)(),{replyToMessageId:o}=t;let{senderId:a}=t;n&&(a=n.userId);const s=a?(0,c.dy)(r,a):void 0,l=(0,i.N5)(t),h=l&&o?(0,c.hj)(r,e.id,o):void 0,{targetUserIds:m,targetChatId:p}=l||{},g=m?m.map((e=>(0,c.dy)(r,e))).filter(Boolean):void 0,v=(0,i.zX)(e),y=v?(0,c.dy)(r,v):void 0;let b;if((0,i.Sm)(e,(0,c.dZ)(r),(0,c.NJ)(r)))if((0,i.Lo)(t)){const n=e&&((0,i.eA)(e)||t.senderId===t.chatId);b=(0,d.D)(f.i0,t,n?void 0:s,n?e:void 0,g,h,p,{asPlainText:!0})}else{const n=(0,i.zF)(f.i0,e.id,s),r=(0,i.MK)(f.i0,t,!1,60,!1);b=n?`${n}: ${r}`:r}else b="New message";return{title:(0,i.U)(f.i0,e,y),body:b}}(t,n,y);if(g()){var E;null!==(E=navigator.serviceWorker)&&void 0!==E&&E.controller&&navigator.serviceWorker.controller.postMessage({type:"showMessageNotification",payload:{title:w,body:C,icon:I,chatId:t.id,messageId:n.id,reaction:null==y?void 0:y.reaction}})}else{const e=(0,u.Sv)(),r={body:C,icon:I,badge:I,tag:String(n.id)};"vibrate"in navigator&&(r.vibrate=[200,100,200]);const o=new Notification(w,r);o.onclick=()=>{o.close(),e.focusMessage({chatId:t.id,messageId:n.id}),y&&e.startActiveReaction({messageId:n.id,reaction:y.reaction}),window.focus&&window.focus()},o.onshow=()=>{b(String(n.id)||t.id)}}}function M(e){var t;!a.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,{$:()=>a,L:()=>d});const r="kz_version",o=["Z","K"];function d(e){localStorage.setItem(r,JSON.stringify(e))}function a(){(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:()=>a,WZ:()=>s,g3:()=>u,un:()=>i});var r=n(782);const o="X",d="XXX XXX XXX XXX";function a(e,t){return e.filter((e=>e.iso2===t))}function u(e){var t;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",o=n.replace(/[^\d+]+/g,"");o.startsWith("+")&&(o=o.substr(1));const d=e.filter((e=>o.startsWith(e.countryCode))),a=(0,r.xH)(d.map((e=>(e.prefixes||[""]).map((t=>({code:`${e.countryCode}${t}`,country:e})))))),u=a.filter((e=>{let{code:t}=e;return o.startsWith(t)})).sort(((e,t)=>e.code.length-t.code.length));return null===(t=u[u.length-1])||void 0===t?void 0:t.country}function i(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),a=[];let u=0;for(let e=0;e{n.d(t,{V:()=>a,q:()=>d});var r=n(6137),o=n(6590);function d(e){const t="thread"!==e.type?`_${e.type}`:-1!==e.threadId?`_${e.threadId}`:"";return`${e.chatId}${t}`}function a(){if(!o.Oy)return;const[e,t]=o.Oy.replace(/^#/,"").split("_");if(null==e||!e.match(/^-?\d+$/))return;const n=["thread","pinned","scheduled"].includes(t);return{chatId:e,type:Boolean(t)&&n?t:"thread",threadId:Boolean(t)&&!n?Number(t):r._f}}},9118:(e,t,n)=>{function r(e,t){let n,r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],o=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return function(){for(var d=arguments.length,a=new Array(d),u=0;u{o&&e(...a),n=void 0}),t)}}function o(e,t){let n,r,o,d=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function(){r=!0;for(var a=arguments.length,u=new Array(a),i=0;i{if(!r)return self.clearInterval(n),void(n=void 0);r=!1,e(...o)}),t))}}function d(e){return i(v,e)}function a(e){return i(y,e)}function u(e){return i(b,e)}function i(e,t){let n,r=!1;return function(){for(var o=arguments.length,d=new Array(o),a=0;a{r=!1,t(...n)})))}}function s(e,t){self.requestIdleCallback?self.requestIdleCallback(e,{timeout:t}):b(e)}n.d(t,{$6:()=>u,D0:()=>y,Ds:()=>r,Gq:()=>w,P2:()=>o,Pn:()=>l,Q8:()=>s,R3:()=>b,T2:()=>v,mS:()=>d,wO:()=>c,wT:()=>a,zD:()=>I});const c=e=>new Promise((t=>{setTimeout((()=>t()),e)}));function l(){return new Promise((e=>{v(e)}))}let f,h,m,p,g;function v(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[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 y(e){v(e,!0)}function b(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[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 I(e){b(e,!0)}function w(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[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,{W:()=>d,Z:()=>o});try{r=/[^\p{L}\p{M}]+/iu}catch(e){r=/[^\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},3100:(e,t,n)=>{n.d(t,{f3:()=>m,jv:()=>l,ti:()=>s,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=(!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise((function(e){var t=function(){return indexedDB.databases().finally(e)};o=setInterval(t,100),t()})).finally((function(){return clearInterval(o)})):Promise.resolve()).then((()=>{const e=indexedDB.open("keyval-store");return e.onupgradeneeded=()=>e.result.createObjectStore(t),r(e)}));var o;return(e,r)=>n.then((n=>r(n.transaction(t,e).objectStore(t))))}(0,"keyval")),o}var a=n(3716),u=n(9524);const i=[1,2,3,4,5];function s(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(e&&localStorage.getItem(a.Vx))return!0;const t=localStorage.getItem(a.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(a.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(){[a.b_,"dc",...i.map((e=>`dc${e}_auth_key`)),...i.map((e=>`dc${e}_hash`))].forEach((e=>{localStorage.removeItem(e)}))}function f(){if(!s())return;const e=JSON.parse(localStorage.getItem(a.b_)),t=Number(e.dcID),n={},r={};return i.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){a.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(a.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){a.eM&&console.warn("Failed to load legacy session",e)}}async function m(){localStorage.removeItem(a.Vx);const e=await function(e=d()){return e("readonly",(e=>{if(e.getAllKeys)return r(e.getAllKeys());const t=[];return function(e,t){return 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([u.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)))])}},7370:(e,t,n)=>{n.d(t,{Z:()=>h});var r=n(9933),o=n(9118);const d=JSON.parse('{"--color-primary":["#3390EC","#8774E1"],"--color-primary-opacity":["#50A2E980","#8378DB80"],"--color-primary-shade":["#4a95d6","#7b71c6"],"--color-background":["#FFFFFF","#212121"],"--color-background-compact-menu":["#FFFFFFBB","#212121DD"],"--color-background-compact-menu-reactions":["#FFFFFFEB","#212121DD"],"--color-background-compact-menu-hover":["#00000011","#00000066"],"--color-background-secondary":["#f4f4f5","#0F0F0F"],"--color-background-secondary-accent":["#E4E4E5","#100f10"],"--color-background-own":["#EEFFDE","#766AC8"],"--color-background-own-apple":["#DCF8C5","#766AC8"],"--color-background-selected":["#F4F4F5","#2C2C2C"],"--color-background-own-selected":["#d0ffac","#6549d4"],"--color-chat-hover":["#F4F4F5","#2C2C2C"],"--color-chat-active":["#3390EC","#766AC8"],"--color-item-active":["#ededed","#292929"],"--color-text":["#000000","#FFFFFF"],"--color-text-secondary":["#707579","#AAAAAA"],"--color-icon-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","#8775DA"],"--color-reply-own-hover-apple":["#cbefb7","#8775DA"],"--color-reply-own-active":["#C5ECBE","#917DEA"],"--color-reply-own-active-apple":["#bae6a8","#917DEA"],"--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"],"--color-message-reaction":["#ebf3fd","#2b2a35"],"--color-message-reaction-hover":["#c5def9","#343147"],"--color-message-reaction-own":["#cef0ba","#675CAF"],"--color-message-reaction-hover-own":["#b5e0a4","#5B529B"]}');let a=!1;const u=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i,i=new Set(["--color-primary-shade","--color-text-secondary"]),s=(e,t,n)=>(1-n)*e+n*t,c=Object.keys(d).map((e=>({property:e,colors:[l(d[e][0]),l(d[e][1])]})));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){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;c.forEach((r=>{let{property:o,colors:d}=r;const a=Math.round(s(d[e].r,d[t].r,n)),u=Math.round(s(d[e].g,d[t].g,n)),c=Math.round(s(d[e].b,d[t].b,n)),l=void 0!==d[e].a?Math.round(s(d[e].a,d[t].a,n)):void 0;document.documentElement.style.setProperty(o,void 0!==l?`rgba(${a},${u},${c},${l/255})`:`rgb(${a},${u},${c})`),i.has(o)&&document.documentElement.style.setProperty(`${o}-rgb`,`${a},${u},${c}`)}))}const h=(e,t)=>{const n="dark"===e,d=a&&t,u=n?0:1,i=n?1:0,s=Date.now(),c=document.querySelector('meta[name="theme-color"]');document.documentElement.classList.remove("theme-"+(n?"light":"dark")),a&&document.documentElement.classList.add("no-animations"),document.documentElement.classList.add(`theme-${e}`),c&&c.setAttribute("content",n?"#212121":"#fff"),setTimeout((()=>{document.documentElement.classList.remove("no-animations")}),500),a=!0,d?(0,o.T2)((()=>{(0,r.cK)((()=>{const e=Math.min((Date.now()-s)/200,1);return f(u,i,function(e){return 1-(1-e)**3.5}(e)),e<1}))})):f(u,i)}},2155:(e,t,n)=>{n.d(t,{Xv:()=>i,bi:()=>u,kh:()=>d});var r=n(3681),o=n(4284);function d(e){return String(e).replace(/\d(?=(\d{3})+$)/g,"$& ")}function a(e){return".0"===String(e.toFixed(1)).substr(-2)?Math.round(e):e.toFixed(1).replace(".",",")}function u(e){return e<1e3?e:e<1e6?`${a(e/1e3)}K`:`${a(e/1e6)}M`}const i=(0,n(5155).Z)((function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]: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){return!e||!t||e.length<=t?e:`${e.substring(0,t)}...`}n.d(t,{Z:()=>r})},862:(e,t,n)=>{n.d(t,{Hu:()=>i,_y:()=>s,p6:()=>c});var r=n(7361),o=n(1394),d=n(9118);let a,u;const i="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";async function s(e,t){for(l();!u.wasmReady;)await(0,d.wO)(2e3);const{result:n,width:r,height:o}=await function(e,t){return new Promise((n=>{u.requests||(u.requests=new Map),u.requests.set(e,n),u.postMessage({id:e,blob:t})}))}(e,t);if(r&&o)return function(e){let{result:t,width:n,height:r}=e;return a||(a=document.createElement("canvas")),new Promise((e=>{const o=new ImageData(t,n,r);a.width=n,a.height=r,a.getContext("2d").putImageData(o,0,0),a.toBlob((t=>{e(null!=t?t: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 s(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(){u||(u=new Worker(new URL(n.p+n.u(536),n.b)),u.wasmReady=!1,u.onmessage=f)}function f(e){const{id:t}=e.data;switch(e.data.type){case"initialized":u.wasmReady=!0;break;case"result":if(u.requests.has(t)){const n=u.requests.get(t);u.requests.delete(t),n(e.data)}}}},1622:(e,t,n)=>{n.d(t,{IT:()=>l,W8:()=>h,px:()=>f});var r=n(3716),o=n(3555),d=n(3100);const a=["t.me","telegram.me"].map((e=>`//${e}/_websync_?`)),u=`${r.Ji} Z`,i="tgme_sync",s=()=>Math.floor(Number(new Date)/1e3);let c;const l=e=>{const t=s(),{canRedirect:n,ts:r}=JSON.parse(localStorage.getItem(i)||"{}");return n!==e||r+86400<=t?Promise.all(a.map((t=>new Promise(((n,r)=>{const o=document.createElement("script"),d=()=>Boolean(document.body.removeChild(o));o.src=t+new URLSearchParams({authed:Number(e).toString(),version:u}),document.body.appendChild(o),o.onload=()=>{(e=>{const t=s();localStorage.setItem(i,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=s(),{ts:t}=JSON.parse(localStorage.getItem(i)||"{}"),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))}function h(){localStorage.removeItem(i)}},3858:(e,t,n)=>{n.d(t,{Z:()=>h,z:()=>l});var r=n(9118),o=n(3716),d=n(7361);const a=d.wB&&f(),u=window.innerHeight;let i=l(),s=!1;const c=(0,r.P2)((()=>{i=l(),!s&&((i.width<=o.l3||i.width<=o.u_&&i.height<=o.rO)!==d.wB||d.wB&&a!==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:()=>i,getIsKeyboardVisible:()=>u>i.height,disableRefresh:function(){s=!0},enableRefresh:function(){s=!1}}},5155:(e,t,n)=>{n.d(t,{Z:()=>o});const r=new WeakMap;function o(e){return function(){let t=r.get(e);for(var n=arguments.length,o=new Array(n),d=0;d{e.exports=n.p+"app-inactive.bc7953c2dfebcabce2c4..png"},2162:(e,t,n)=>{e.exports=n.p+"monkey.a3d5fcdc50b18dc55695..svg"},5523:(e,t,n)=>{e.exports=n.p+"reaction-thumbs.f920d3f2147d986b6cbe..png"},4128:(e,t,n)=>{e.exports=n.p+"telegram-logo.1b2bb5b107f046ea9325..svg"}},u={};function i(e){var t=u[e];if(void 0!==t)return t.exports;var n=u[e]={exports:{}};return a[e].call(n.exports,n,n.exports,i),n.exports}i.m=a,i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,i.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);i.r(o);var d={};e=e||[null,t({}),t([]),t(t)];for(var a=2&r&&n;"object"==typeof a&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach((e=>d[e]=()=>n[e]));return d.default=()=>n,i.d(o,d),o},i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.f={},i.e=e=>Promise.all(Object.keys(i.f).reduce(((t,n)=>(i.f[n](e,t),t)),[])),i.u=e=>e+"."+{13:"1cb726dfb0fe77ff16db",99:"a19f6cfb125132c4ae9e",133:"e050778acd78ac17365a",161:"e3dd8735bd9f827bebc6",354:"71017c16320a06ddc8da",395:"368d08862d9c65a1cf98",472:"38e2fa9338b8e031169b",501:"17afb8957510497ebb61",524:"e3a446e0b4e9c7ce5ef9",536:"51c4121ec6034fff4884",616:"dfb0d60d06da102bbad4",654:"229871d7a07987919e6c",742:"e09d8d2bec0ce4cf0543",745:"7f9b9b63ef7b71c5b2d7",878:"ba2ac4194b79d543b70f",888:"3bcf93fb3c92294b2737",915:"7c6d5a7308348c57bbbd",941:"1399f916762c873a48a2",970:"81d005f8fdd6b7e03eb7",993:"c7c8681e7135da951723"}[e]+".js",i.miniCssF=e=>e+"."+{13:"1cb726dfb0fe77ff16db",133:"e050778acd78ac17365a",395:"368d08862d9c65a1cf98",472:"38e2fa9338b8e031169b",616:"dfb0d60d06da102bbad4",654:"229871d7a07987919e6c",878:"ba2ac4194b79d543b70f"}[e]+".css",i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n={},r="telegram-t:",i.l=(e,t,o,d)=>{if(n[e])n[e].push(t);else{var a,u;if(void 0!==o)for(var s=document.getElementsByTagName("script"),c=0;c{a.onerror=a.onload=null,clearTimeout(h);var o=n[e];if(delete n[e],a.parentNode&&a.parentNode.removeChild(a),o&&o.forEach((e=>e(r))),t)return t(r)},h=setTimeout(f.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=f.bind(null,a.onerror),a.onload=f.bind(null,a.onload),u&&document.head.appendChild(a)}},i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;i.g.importScripts&&(e=i.g.location+"");var t=i.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(/\/[^\/]+$/,"/"),i.p=e})(),o=e=>new Promise(((t,n)=>{var r=i.miniCssF(e),o=i.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 a=d&&("load"===d.type?"missing":d.type),u=d&&d.target&&d.target.href||t,i=new Error("Loading CSS chunk "+e+" failed.\n("+u+")");i.code="CSS_CHUNK_LOAD_FAILED",i.type=a,i.request=u,o.parentNode.removeChild(o),r(i)}},o.href=t,document.head.appendChild(o)})(e,o,t,n)})),d={179:0},i.f.miniCss=(e,t)=>{d[e]?t.push(d[e]):0!==d[e]&&{13:1,133:1,395:1,472:1,616:1,654:1,878:1}[e]&&t.push(d[e]=o(e).then((()=>{d[e]=0}),(t=>{throw delete d[e],t})))},(()=>{i.b=document.baseURI||self.location.href;var e={179:0};i.f.j=(t,n)=>{var r=i.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=i.p+i.u(t),a=new Error;i.l(d,(n=>{if(i.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;a.message="Loading chunk "+t+" failed.\n("+o+": "+d+")",a.name="ChunkLoadError",a.type=o,a.request=d,r[1](a)}}),"chunk-"+t,t)}};var t=(t,n)=>{var r,o,[d,a,u]=n,s=0;if(d.some((t=>0!==e[t]))){for(r in a)i.o(a,r)&&(i.m[r]=a[r]);u&&u(i)}for(t&&t(n);s{i(3592);var e=i(3716),t=i(3555),n=i(7361),r=i(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.Sv)(),a=o.payload;switch(o.type){case"focusMessage":d.focusMessage&&d.focusMessage(a),d.startActiveReaction&&a.reaction&&d.startActiveReaction({messageId:a.messageId,reaction:a.reaction});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{if(!navigator.serviceWorker.controller){const t=await navigator.serviceWorker.getRegistrations();t.length&&(e.eM&&console.log("[SW] Hard reload detected, re-enabling Service Worker"),await Promise.all(t.map((e=>e.unregister()))))}await navigator.serviceWorker.register(new URL(i.p+i.u(524),i.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.Sv)().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 a=i(4050),u=i(2916);const s={isLeftColumnShown:!0,isChatInfoShown:!1,newChatMembersProgress:i(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:{volume:e.Qx,playbackRate:e.mw,isMuted:!1},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,isConnectionStatusMinimized:!0},themes:{light:{isBlurred:!0,patternColor:e.g},dark:{isBlurred:!0,patternColor:e.Vv}},privacy:{},notifyExceptions:{}},twoFaSettings:{},activeReactions:{},shouldShowContextMenuHint:!0,activeDownloads:{byChatId:{}},serviceNotifications:[],statistics:{byChatId:{}}};var c=i(5116),l=i(6137),f=i(9118),h=i(8674),m=i(782),p=i(1192),g=i(3100),v=i(5780),y=i(5806),b=i(6974);const I=(0,f.P2)((()=>(0,f.Q8)(P)),5e3,!1);let w,C=!1;function S(){C=!0,w=(0,f.Gq)(P,!0),window.addEventListener("blur",P),(0,c.ll)(I)}function E(){C=!1,(0,c.Iq)(I),window.removeEventListener("blur",P),w&&w()}function P(){if(!C||(0,h.zG)())return;const n=(0,t.Rd)();if(n.isLoggingOut)return;const r={...s,...(0,m.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},mediaViewer:{volume:n.mediaViewer.volume,playbackRate:n.mediaViewer.playbackRate,isMuted:n.mediaViewer.isMuted},isChatInfoShown:M(n),users:A(n),chats:k(n),messages:T(n),globalSearch:{recentlyFoundChatIds:n.globalSearch.recentlyFoundChatIds},settings:N(n),chatFolders:L(n),groupCalls:R(n),availableReactions:x(n)},o=JSON.stringify(r);localStorage.setItem(e.Uh,o)}function M(t){return window.innerWidth>e._m&&t.isChatInfoShown}function A(t){var n,r,o,d,a;const{users:{byId:u,statusesById:i},currentUserId:s}=t,{chatId:c}=(0,p.Bt)(t)||{},l=null===(n=(0,p.P2)(t))||void 0===n?void 0:n.map((e=>{let{id:t}=e;return t})),f=(0,m.Tw)([...s?[s]:[],...c&&(0,y.YC)(c)?[c]:[],...l||[],...t.topPeers.userIds||[],...(null===(r=(0,b.gO)(e.Nf))||void 0===r?void 0:r.filter(y.YC))||[],...(null===(o=(0,b.gO)(e.WS))||void 0===o?void 0:o.filter(y.YC))||[],...(null===(d=t.contactList)||void 0===d?void 0:d.userIds)||[],...(null===(a=t.globalSearch.recentlyFoundChatIds)||void 0===a?void 0:a.filter(y.YC))||[],...Object.keys(u)]).slice(0,e.lO);return{byId:(0,m.ei)(u,f),statusesById:(0,m.ei)(i,f)}}function k(t){const{chats:{byId:n},currentUserId:r}=t,o=(0,p.jr)(t),d=(0,m.Tw)([...r?[r]:[],...o?[o.id]:[],...(0,b.gO)(e.Nf)||[],...(0,b.gO)(e.WS)||[],...t.globalSearch.recentlyFoundChatIds||[],...Object.keys(n)]).slice(0,e.gJ);return{...t.chats,isFullyLoaded:{},byId:(0,m.ei)(t.chats.byId,d)}}function T(t){var n;const{currentUserId:r}=t,o={},{chatId:d}=(0,p.Bt)(t)||{};return[...d?[d]:[],...r?[r]:[],...(null===(n=(0,b.gO)(e.Nf))||void 0===n?void 0:n.slice(0,e.Rk))||[]].forEach((e=>{const n=t.messages.byChatId[e];if(!n)return;const r=n.threadsById[l._f];r&&r.viewportIds&&(o[e]={byId:(0,m.ei)(n.byId,r.viewportIds),threadsById:{[l._f]:r}})})),{byChatId:o,messageLists:[],sponsoredByChatId:{}}}function N(e){const{byKey:t,themes:n}=e.settings;return{byKey:t,themes:n,privacy:{},notifyExceptions:{}}}function L(e){return{...e.chatFolders,activeChatFolder:0}}function R(e){return{...e.groupCalls,byId:{},activeGroupCallId:void 0,isGroupCallPanelHidden:void 0,isFallbackConfirmOpen:void 0}}function x(e){var t;return null===(t=e.availableReactions)||void 0===t?void 0:t.map((e=>(0,m.ei)(e,["reaction","staticIcon","title","isInactive"])))}e.sd||((0,t.iw)("saveSession",(()=>{C||S()})),(0,t.iw)("reset",(()=>{localStorage.removeItem(e.Uh),C&&E()}))),(0,t.iw)("init",(()=>{const t=(0,m.Xh)(s);return function(t){if(!e.sd)return(0,g.ti)(!0)?(S(),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:a,...u}=t.settings.byKey;t.settings.byKey={...u,canAutoLoadPhotoFromContacts:e,canAutoLoadVideoFromContacts:e,canAutoLoadPhotoInPrivateChats:n,canAutoLoadVideoInPrivateChats:n,canAutoLoadPhotoInGroups:r,canAutoLoadVideoInGroups:r,canAutoLoadPhotoInChannels:o,canAutoLoadVideoInChannels:o,canAutoPlayVideos:d,canAutoPlayGifs:a}}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),void 0===t.mediaViewer.volume&&(t.mediaViewer.volume=e.Qx),void 0===t.mediaViewer.playbackRate&&(t.mediaViewer.playbackRate=e.mw),t.groupCalls||(t.groupCalls=n.groupCalls),t.users.statusesById||(t.users.statusesById={}),t.messages.sponsoredByChatId||(t.messages.sponsoredByChatId={}),t.activeReactions||(t.activeReactions={})}(o,t);const d={...t,...o},a=n.wB?void 0:(0,v.V)();return{...d,messages:{...d.messages,messageLists:a?[a]:[]}}}(t)):void E()}(t)||t}));var B=i(3858);const F="tt-active-tab",O=String(Date.now()+Math.random());let D;localStorage.setItem(F,O);const Z=window.setInterval((()=>{D&&localStorage.getItem(F)!==O&&(D(),clearInterval(Z))}),2e3);var _=i(706),$=(i(9005),i(3456),i(5456),i(1371),i(8304),i(6590)),U=i(2825),j=i(1212),V=i(1394);const W=["400 1em Roboto","500 1em Roboto"];function G(){if("fonts"in document)return Promise.all(W.map((e=>document.fonts.load(e))))}var H=i(647),z=i(9203),K=i(6752),J=i(4128),q=i(5523),Y=i(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,U.RT)(t);return r?H.he(r,l.IU.BlobUrl):void 0})))}const X={main:()=>Promise.all([(0,z.$y)(z.gl.Main,"Main").then(G),Q(),(0,V.pt)(q)]),authPhoneNumber:()=>Promise.all([G(),(0,V.pt)(J)]),authCode:()=>(0,V.pt)(Y),authPassword:()=>(0,V.pt)(Y),authQrCode:G},ee=(0,t.c$)((e=>{const t=(0,p.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,p.Jf)(e),leftColumnWidth:e.leftColumnWidth}}))((e=>{let{page:n,children:r,hasCustomBackground:o,hasCustomBackgroundColor:d,isRightColumnShown:u,shouldSkipHistoryAnimations:i,leftColumnWidth:s}=e;const{setIsUiReady:c}=(0,t.Sv)(),[l,h]=(0,_.Z)(),{shouldRender:m,transitionClassNames:p}=(0,j.Z)(!l,void 0,!0);return(0,a.d4)((()=>{let e;return Promise.race([(0,f.wO)(700),(async()=>{try{await X[n]()}catch(e){}})()]).then((()=>{h(),c({uiReadyState:1}),e=window.setTimeout((()=>{c({uiReadyState:2})}),1e3)})),()=>{e&&(clearTimeout(e),e=void 0),c({uiReadyState:0})}}),[]),a.ZP.createElement("div",{id:"UiLoader"},r,m&&!i&&a.ZP.createElement("div",{className:(0,K.Z)("mask",p)},"main"===n?a.ZP.createElement(a.ZP.Fragment,null,a.ZP.createElement("div",{className:"left",style:s?`width: ${s}px`:void 0}),a.ZP.createElement("div",{className:(0,K.Z)("middle",o&&"custom-bg-image",d&&"custom-bg-color",u&&"with-right-column")}),u&&a.ZP.createElement("div",{className:"right"})):a.ZP.createElement("div",{className:"blank"})))}));var te=i(6272),ne=i(711),re=i(9107);const oe=(e,t)=>{const[n,r]=(0,a.eJ)();return e&&ne.Pn(e,t).then(r),n};function de(){let e=navigator.language;return e&&"pt-br"!==e&&(e=e.substr(0,2)),e}var ae=i(231),ue=i(4605),ie=i(7687),se=i(4288),ce=i(5765),le=i(2340),fe=i(4284),he=i(9290),me=i(3106),pe=i(8964),ge=i(9204);const ve=200+e.fK,ye=(0,a.X$)((0,t.c$)((e=>{const{countryList:{phoneCodes:t}}=e;return{phoneCodeList:t}}))((e=>{let{id:t,value:n,isLoading:r,onChange:o,phoneCodeList:d}=e;const u=(0,re.Z)(),i=(0,a.sO)(null),[s,c]=(0,a.eJ)(),[l,f]=(0,a.eJ)([]),h=(0,a.I4)((e=>{c(e),f(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(!t.length)return e;const n=(0,ce.W)(t);return e.filter((e=>n(e.defaultName)||e.name&&n(e.name)))}(d,e))}),[d]);(0,he.Z)((e=>{let[t]=e;0===(null==t?void 0:t.length)&&d.length>0&&h(s)}),[d,h]);const m=(0,a.I4)((e=>{o(e),setTimeout((()=>h(void 0)),ve)}),[o,h]),p=(0,a.I4)((e=>{h(e.currentTarget.value)}),[h]),g=(0,a.I4)((e=>{if(8!==e.keyCode)return;const t=e.currentTarget;n&&void 0===s&&(t.value=""),h(t.value)}),[s,h,n]),v=(0,a.I4)((e=>{let{onTrigger:o,isOpen:d}=e;const c=()=>{if(d)return;setTimeout((()=>{i.current.select()}),50),o();const e=document.getElementById("auth-phone-number-form");e.scrollTo({top:e.scrollHeight,behavior:"smooth"})},l=null!=s?s:(null==n?void 0:n.name)||(null==n?void 0:n.defaultName)||"";return a.ZP.createElement("div",{className:(0,K.Z)("input-group",n&&"touched")},a.ZP.createElement("input",{ref:i,className:(0,K.Z)("form-control",d&&"focus"),type:"text",id:t,value:l,autoComplete:"off",onClick:c,onFocus:c,onInput:e=>{p(e),c()},onKeyDown:g}),a.ZP.createElement("label",null,u("Login.SelectCountry.Title")),r?a.ZP.createElement(ge.Z,{color:"black"}):a.ZP.createElement("i",{onClick:c,className:(0,K.Z)("css-icon-down",d&&"open")}))}),[s,p,g,t,r,u,n]);return a.ZP.createElement(me.Z,{className:"CountryCodeInput",trigger:v},l.map((e=>a.ZP.createElement(pe.Z,{key:`${e.iso2}-${e.countryCode}`,className:n&&e.iso2===n.iso2?"selected":"",onClick:()=>m(e)},a.ZP.createElement("span",{className:"country-flag"},(0,le.Z)((0,fe.Wg)(e.iso2),["hq_emoji"])),a.ZP.createElement("span",{className:"country-name"},e.name||e.defaultName),a.ZP.createElement("span",{className:"country-code"},"+",e.countryCode)))),!l.length&&a.ZP.createElement(pe.Z,{key:"no-results",className:"no-results",disabled:!0},a.ZP.createElement("span",null,u("lng_country_none"))))})));let be=!1;const Ie=(0,a.X$)((0,t.c$)((e=>{const{settings:{byKey:{language:t}},countryList:{phoneCodes:n}}=e;return{...(0,m.ei)(e,["connectionState","authState","authPhoneNumber","authIsLoading","authIsLoadingQrCode","authError","authRememberMe","authNearestCountry"]),language:t,phoneCodeList:n}}))((e=>{let{connectionState:r,authState:o,authPhoneNumber:d,authIsLoading:u,authIsLoadingQrCode:i,authError:s,authRememberMe:c,authNearestCountry:l,phoneCodeList:f,language:h}=e;const{setAuthPhoneNumber:m,setAuthRememberMe:p,loadNearestCountry:g,loadCountryList:v,clearAuthError:y,goToAuthQrCode:b,setSettingOption:I}=(0,t.Sv)(),w=(0,re.Z)(),C=(0,a.sO)(null),S=de(),E=oe(S,"ContinueOnThisLanguage"),[P,M]=(0,a.eJ)(),[A,k]=(0,a.eJ)(),[T,N]=(0,a.eJ)(!1),[L,R]=(0,a.eJ)(),[x,B,F]=(0,_.Z)(),O=P?`+${P.countryCode} ${A||""}`:A,D=O&&O.replace(/[^\d]+/g,"").length>=7;(0,a.d4)((()=>{n.$b||C.current.focus()}),[P]),(0,a.d4)((()=>{"connectionStateReady"!==r||l||g()}),[r,l,g]),(0,a.d4)((()=>{"connectionStateReady"===r&&v({langCode:h})}),[r,h,v]),(0,a.d4)((()=>{l&&f&&!P&&!T&&M((0,te.U9)(f,l)[0])}),[P,l,T,f]);const Z=(0,a.I4)((e=>{e.length||k("");const t=f&&(0,te.g3)(f,e),n=!P||t&&t.iso2!==P.iso2||!t&&e.length?t:P;(!P||!n||n&&n.iso2!==P.iso2)&&M(n),k((0,te.un)(e,n))}),[f,P]),$=(0,a.I4)((()=>{B(),(0,ne.m0)(S,(()=>{F(),I({language:S})}))}),[B,I,S,F]);(0,a.d4)((()=>{void 0===A&&d&&Z(d)}),[d,A,Z]),(0,a.bt)((()=>{C.current&&L&&C.current.setSelectionRange(...L)}),[L]);const U=(0,a.sO)(!1),j=(0,a.I4)((()=>{U.current=!0,requestAnimationFrame((()=>{U.current=!1}))}),[]),W=(0,a.I4)((e=>{M(e),k("")}),[]),H=(0,a.I4)((e=>{s&&y(),be||(be=!0,G(),(0,V.pt)(Y));const{value:t,selectionStart:r,selectionEnd:o}=e.target;R(r&&o&&o1&&!U.current;Z(d?`${P.countryCode} ${t}`:t)}),[s,y,P,O,Z]),z=(0,a.I4)((e=>{p(e.target.checked)}),[p]),K="authorizationStateWaitPhoneNumber"===o;return a.ZP.createElement("div",{id:"auth-phone-number-form",className:"custom-scroll"},a.ZP.createElement("div",{className:"auth-form"},a.ZP.createElement("div",{id:"logo"}),a.ZP.createElement("h2",null,"Telegram"),a.ZP.createElement("p",{className:"note"},w("StartText")),a.ZP.createElement("form",{action:"",onSubmit:function(e){e.preventDefault(),u||D&&m({phoneNumber:O})}},a.ZP.createElement(ye,{id:"sign-in-phone-code",value:P,isLoading:!l&&!P,onChange:W}),a.ZP.createElement(ie.Z,{ref:C,id:"sign-in-phone-number",label:w("Login.PhonePlaceholder"),value:O,error:s&&w(s),inputMode:"tel",onChange:H,onPaste:n.s$?j:void 0}),a.ZP.createElement(ue.Z,{id:"sign-in-keep-session",label:"Keep me signed in",checked:Boolean(c),onChange:z}),D&&(K?a.ZP.createElement(ae.Z,{type:"submit",ripple:!0,isLoading:u},w("Login.Next")):a.ZP.createElement(se.Z,null)),K&&a.ZP.createElement(ae.Z,{isText:!0,ripple:!0,isLoading:i,onClick:b},w("Login.QR.Login")),S&&S!==h&&E&&a.ZP.createElement(ae.Z,{isText:!0,isLoading:x,onClick:$},E))))})));var we=i(8778);const Ce=(0,a.X$)((()=>{const e=(0,we.Z)(z.gl.Auth,"AuthCode");return e?a.ZP.createElement(e,null):a.ZP.createElement(se.Z,null)})),Se=(0,a.X$)((()=>{const e=(0,we.Z)(z.gl.Auth,"AuthPassword");return e?a.ZP.createElement(e,null):a.ZP.createElement(se.Z,null)})),Ee=(0,a.X$)((()=>{const e=(0,we.Z)(z.gl.Auth,"AuthRegister");return e?a.ZP.createElement(e,null):a.ZP.createElement(se.Z,null)}));let Pe=null;class Me{}Me.render=function(e,t){Pe(e,t)},self.QrCreator=Me,function(e){function t(t,n,r,o){var d={},a=e(r,n);a.u(t),a.J(),o=o||0;var u=a.h(),i=a.h()+2*o;return d.text=t,d.level=n,d.version=r,d.O=i,d.a=function(e,t){return t-=o,!(0>(e-=o)||e>=u||0>t||t>=u)&&a.a(e,t)},d}function n(e,t,n,r,o,d,a,u,i,s){function c(t,n,r,o,a,u,i){t?(e.lineTo(n+u,r+i),e.arcTo(n,r,o,a,d)):e.lineTo(n,r)}a?e.moveTo(t+d,n):e.moveTo(t,n),c(u,r,n,r,o,-d,0),c(i,r,o,t,o,0,-d),c(s,t,o,t,n,d,0),c(a,t,n,r,n,0,d)}function r(e,t,n,r,o,d,a,u,i,s){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)}a&&c(t,n,d,d),u&&c(r,n,-d,d),i&&c(r,o,-d,-d),s&&c(t,o,d,-d)}function o(e,o){e:{var d=o.text,a=o.v,u=o.N,i=o.K,s=o.P;for(u=Math.max(1,u||1),i=Math.min(40,i||40);u<=i;u+=1)try{var c=t(d,a,u,s);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)),a=c.O,i=o.size/a,d.beginPath(),s=0;sMath.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};Pe=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,a){function u(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 i(e,n){for(var a=l=4*o+17,i=Array(a),m=0;m=v;v+=1)for(var y=-2;2>=y;y+=1)c[p+v][g+y]=-2==v||2==v||-2==y||2==y||0==v&&0==y}for(a=8;ai;i+=1)m=!e&&1==(a>>i&1),c[6>i?i:8>i?i+1:l-15+i][8]=m,c[8][8>i?l-i-1:9>i?15-i:14-i]=m;if(c[l-8][8]=!e,7<=o){for(a=r.A(o),i=0;18>i;i+=1)m=!e&&1==(a>>i&1),c[Math.floor(i/3)][i%3+l-8-3]=m;for(i=0;18>i;i+=1)m=!e&&1==(a>>i&1),c[i%3+l-8-3][Math.floor(i/3)]=m}if(null==f){for(e=d.I(o,s),a=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}(),i=0;i8*m)throw Error("code length overflow. ("+a.f()+">"+8*m+")");for(a.f()+4<=8*m&&a.put(0,4);0!=a.f()%8;)a.m(!1);for(;!(a.f()>=8*m||(a.put(236,8),a.f()>=8*m));)a.put(17,8);var b=0;for(m=i=0,p=Array(e.length),g=Array(e.length),v=0;vv;v+=1)null==c[i][g-v]&&(y=!1,p>>m&1)),n(i,g-v)&&(y=!y),c[i][g-v]=y,-1==--m&&(p+=1,m=7));if(0>(i+=a)||l<=i){i-=a,a=-a;break}}}var s=n[a],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){i(!0,n);var o=r.D(m);(0==n||e>o)&&(e=o,t=n)}i(!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()),a=0;ar?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]],r={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=u;u+=1)if(!(0>r+u||t<=r+u))for(var i=-1;1>=i;i+=1)0>o+i||t<=o+i||(0!=u||0!=i)&&a==e.a(r+u,o+i)&&(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]],r={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}}))((n=>{let{connectionState:r,authState:o,authQrCode:d,language:u}=n;const{returnToAuthPhoneNumber:i,setSettingOption:s}=(0,t.Sv)(),c=de(),l=(0,re.Z)(),f=(0,a.sO)(null),h=oe(c,"ContinueOnThisLanguage"),[m,p,g]=(0,_.Z)();(0,a.d4)((()=>{if(!d||"connectionStateReady"!==r)return;const e=f.current;e.innerHTML="",e.classList.remove("pre-animate"),Ae.render({text:`tg://login?token=${d.token}`,radius:.5,ecLevel:"M",fill:"#4E96D4",size:280},e)}),[r,d]),(0,a.d4)((()=>{"connectionStateReady"===r&&(0,ne.m0)(e.sR)}),[r]);const v=(0,a.I4)((()=>{p(),(0,ne.m0)(c,(()=>{g(),s({language:c})}))}),[p,s,c,g]),y="authorizationStateWaitQrCode"===o;return a.ZP.createElement("div",{id:"auth-qr-form",className:"custom-scroll"},a.ZP.createElement("div",{className:"auth-form qr"},d?a.ZP.createElement("div",{key:"qr-container",className:"qr-container pre-animate",ref:f}):a.ZP.createElement("div",{key:"qr-loading",className:"qr-loading"},a.ZP.createElement(se.Z,null)),a.ZP.createElement("h3",null,l("Login.QR.Title")),a.ZP.createElement("ol",null,a.ZP.createElement("li",null,a.ZP.createElement("span",null,l("Login.QR.Help1"))),a.ZP.createElement("li",null,a.ZP.createElement("span",null,(0,le.Z)(l("Login.QR2.Help2"),["simple_markdown"]))),a.ZP.createElement("li",null,a.ZP.createElement("span",null,l("Login.QR.Help3")))),y&&a.ZP.createElement(ae.Z,{isText:!0,onClick:i},l("Login.QR.Cancel")),c&&c!==u&&h&&a.ZP.createElement(ae.Z,{isText:!0,isLoading:m,onClick:v},h)))}))),Te=(0,a.X$)((0,t.c$)((e=>(0,m.ei)(e,["authState"])))((e=>{let{authState:r}=e;const{reset:o,initApi:d,returnToAuthPhoneNumber:u,goToAuthQrCode:i}=(0,t.Sv)();(0,a.d4)((()=>{o(),d()}),[o,d]);const s="iOS"===n.Lt||"Android"===n.Lt;switch((0,$.ZP)(!s&&"authorizationStateWaitPhoneNumber"===r||s&&"authorizationStateWaitQrCode"===r,(()=>{s?u():i()})),(0,a.d4)((()=>(B.Z.disableRefresh(),()=>{B.Z.enableRefresh()})),[]),r){case"authorizationStateWaitCode":return a.ZP.createElement(ee,{page:"authCode",key:"authCode"},a.ZP.createElement(Ce,null));case"authorizationStateWaitPassword":return a.ZP.createElement(ee,{page:"authPassword",key:"authPassword"},a.ZP.createElement(Se,null));case"authorizationStateWaitRegistration":return a.ZP.createElement(Ee,null);case"authorizationStateWaitPhoneNumber":return a.ZP.createElement(ee,{page:"authPhoneNumber",key:"authPhoneNumber"},a.ZP.createElement(Ie,null));case"authorizationStateWaitQrCode":return a.ZP.createElement(ee,{page:"authQrCode",key:"authQrCode"},a.ZP.createElement(ke,null));default:return s?a.ZP.createElement(ee,{page:"authPhoneNumber",key:"authPhoneNumber"},a.ZP.createElement(Ie,null)):a.ZP.createElement(ee,{page:"authQrCode",key:"authQrCode"},a.ZP.createElement(ke,null))}}))),Ne=(0,a.X$)((()=>{const e=(0,we.Z)(z.gl.Main,"Main");return e?a.ZP.createElement(e,null):void 0}));var Le=i(5359);const Re=()=>a.ZP.createElement("div",{id:"AppInactive"},a.ZP.createElement("div",{className:"content"},a.ZP.createElement("img",{src:Le,alt:""}),a.ZP.createElement("h3",{className:"title"},"Such error, many tabs"),a.ZP.createElement("div",{className:"description"},"Telegram supports only one active tab with the app.",a.ZP.createElement("br",null),"Please reload this page to continue using this tab or close it."),a.ZP.createElement("div",{className:"actions"},a.ZP.createElement(ae.Z,{isText:!0,ripple:!0,onClick:()=>{window.location.reload()}},"Reload app"))));function xe(){return a.ZP.createElement(ee,{page:"main",key:"main"},a.ZP.createElement(Ne,null))}const Be=(0,t.c$)((e=>(0,m.ei)(e,["authState"])))((n=>{let{authState:r}=n;const{disconnect:o}=(0,t.Sv)(),[d,u]=(0,_.Z)(!1);if((0,a.d4)((()=>{(0,B.z)(),D=()=>{o(),document.title=`${e.Ti}${e.ou}`,u()}}),[o,u]),d)return a.ZP.createElement(Re,null);if(r)switch(r){case"authorizationStateWaitPhoneNumber":case"authorizationStateWaitCode":case"authorizationStateWaitPassword":case"authorizationStateWaitRegistration":case"authorizationStateWaitQrCode":return a.ZP.createElement(Te,null);case"authorizationStateClosed":case"authorizationStateClosing":case"authorizationStateLoggingOut":case"authorizationStateReady":return xe()}return(0,g.ti)(!0)?xe():a.ZP.createElement(Te,null)}));e.eM&&console.log(">>> INIT"),(0,t.Sv)().init(),e.eM&&console.log(">>> START INITIAL RENDER"),u.Z.render(a.ZP.createElement(Be,null),document.getElementById("root")),e.eM&&console.log(">>> FINISH INITIAL RENDER"),document.addEventListener("dblclick",(()=>{console.warn("GLOBAL STATE",(0,t.Rd)())}))})()})(); -//# sourceMappingURL=main.687698a9e9aa68d75d14.js.map \ No newline at end of file +(()=>{"use strict";var e,t,n,r,o,d,a={1226:(e,t,n)=>{n.d(t,{t9:()=>c,u3:()=>l,g8:()=>s});var r=n(3716),o=n(6926),d=n(9118);let a;const u=new Map,i=new Map;function s(e,t){return a||(r.eM&&console.log(">>> START LOAD WORKER"),a=new Worker(new URL(n.p+n.u(742),n.b)),function(e){a.addEventListener("message",(t=>{let{data:n}=t;if("update"===n.type)e(n.update);else if("methodResponse"===n.type){const e=u.get(n.messageId);e&&(n.error?e.reject(n.error):e.resolve(n.response))}else if("methodCallback"===n.type){var r,o;null===(r=u.get(n.messageId))||void 0===r||null===(o=r.callback)||void 0===o||o.call(r,...n.callbackArgs)}else if("unhandledError"===n.type){var d;throw new Error(null===(d=n.error)||void 0===d?void 0:d.message)}}))}(e),"iOS"===t.platform&&window.addEventListener("focus",(()=>{m(),setTimeout((()=>m()),1e3)}))),f({type:"initApi",args:[t]})}function c(e){if(!a)return void(r.eM&&console.warn("API is not initialized"));for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o{try{await d}catch(e){}})(),d}function l(e){e.isCanceled=!0;const{messageId:t}=i.get(e)||{};t&&a.postMessage({type:"cancelProgress",messageId:t})}function f(e){const t=(0,o.Z)(u),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,i.set(e,r)}return u.set(t,r),d.catch((()=>{})).finally((()=>{u.delete(t),r.callback&&i.delete(r.callback)})),a.postMessage(n),d}const h=Date.now();async function m(){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()}}},6137:(e,t,n)=>{n.d(t,{IU:()=>o.I,Vv:()=>r.Vv,_Q:()=>r._Q,_f:()=>r._f});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,_Q:()=>d,_f:()=>o}),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.Spoiler="MessageEntitySpoiler",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(3555);const d=36,a=2147483647;function u(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 i(e,t){const n=[],r=[],o=e.length;let i,s,c,l,f,h,m,p,g,v,y,b,I;for(i=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(y=(w=e.charCodeAt(m++))-48<10?w-22:w-65<26?w-65:w-97<26?w-97:d,y>=d)throw RangeError("punycode_bad_input(2)");if(y>Math.floor((a-c)/g))throw RangeError("punycode_overflow(1)");if(c+=y*g,b=v<=l?1:v>=l+26?26:v-l,yMath.floor(a/(d-b)))throw RangeError("punycode_overflow(2)");g*=d-b}if(s=n.length+1,l=u(c-p,s,0===p),Math.floor(c/s)>a-i)throw RangeError("punycode_overflow(3)");i+=Math.floor(c/s),c%=s,t&&r.splice(c,0,e.charCodeAt(m-1)-65<26),n.splice(c,0,i),c++}var w;if(t)for(c=0,I=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 s=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{let{url:t,text:n,className:d,children:a,isRtl:u}=e;const{toggleSafeLinkModal:i,openTelegramLink:h}=(0,o.Sv)(),m=a||n,p=t!==m,g=(0,r.I4)((e=>e.ctrlKey||e.altKey||e.shiftKey||e.metaKey||!t||!t.match(s.FS)&&!t.match(s.g$)?!p||(i({url:t}),e.preventDefault(),!1):(e.preventDefault(),h({url:t}),!1)),[p,h,i,t]);if(!t)return;const v=(0,c.Z)(d||"text-entity-link",n.length>50&&"long-word-break-all");return r.ZP.createElement("a",{href:(0,l.X)(t),title:f(t),target:"_blank",rel:"noopener noreferrer",className:v,onClick:g,dir:u?"rtl":"auto"},m)}))},5376:(e,t,n)=>{n.d(t,{K2:()=>o,Oh:()=>a,mD:()=>d,v6:()=>u,yW:()=>r});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 a(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 u(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:()=>y});var r=n(4050),o=n(5806),d=n(8035),a=n(9937),u=n(996),i=n(2340),s=n(6752),c=n(8033),l=n(3555);const f=e=>{let{className:t,sender:n,children:o}=e;const{openChat:d}=(0,l.Sv)(),a=(0,r.I4)((()=>{n&&d({id:n.id})}),[n,d]);return n?r.ZP.createElement(c.Z,{className:(0,s.Z)("UserLink",t),onClick:a},o):o},h=e=>{let{className:t,message:n,children:o}=e;const{focusMessage:d}=(0,l.Sv)(),a=(0,r.I4)((()=>{n&&d({chatId:n.chatId,messageId:n.id})}),[d,n]);return n?r.ZP.createElement(c.Z,{className:(0,s.Z)("MessageLink",t),onClick:a},o):o},m=e=>{let{className:t,chatId:n,children:o}=e;const{openChat:d}=(0,l.Sv)(),a=(0,r.I4)((()=>{n&&d({id:n})}),[n,d]);return n?r.ZP.createElement(c.Z,{className:(0,s.Z)("ChatLink",t),onClick:a},o):o},p=e=>{let{className:t,groupCall:n,children:o}=e;const{joinGroupCall:d}=(0,l.Sv)(),a=(0,r.I4)((()=>{n&&d({id:n.id,accessHash:n.accessHash})}),[n,d]);return n?r.ZP.createElement(c.Z,{className:(0,s.Z)("GroupCallLink",t),onClick:a},o):o},g=32,v=" ";function y(e,t,n,r,o,d,u){let i=arguments.length>7&&void 0!==arguments[7]?arguments[7]:{};if(!t.content.action)return[];const{text:s,translationValues:c,amount:l,currency:f,call:h}=t.content.action,m=[],p=i.asPlainText||i.asTextWithSpoilers,g="Chat.Service.Group.UpdatedPinnedMessage1"!==s||d?s:"Message.PinnedGenericMessage";let y,M=e(g,null!=c&&c.length?c:void 0);return M.includes("%payment_amount%")&&(y=P(M,"%payment_amount%",(0,a.x)(l,f,e.code)),M=y.pop(),m.push(...y)),y=P(M,"%action_origin%",n?C(n,p)||v:r?S(e,r,p)||v:"User"),M=y.pop(),m.push(...y),y=P(M,"%target_user%",o?o.map((e=>C(e,p))).filter(Boolean):"User"),M=y.pop(),m.push(...y),y=P(M,"%message%",d?I(e,d,i):"a message"),M=y.pop(),m.push(...y),y=P(M,"%product%",d?b(d):"a product"),M=y.pop(),m.push(...y),y=P(M,"%target_chat%",u?E(u,p):"another chat"),m.push(...y),i.asPlainText?m.join("").trim():h?w(h,m):m}function b(e){return e.content&&e.content.invoice?e.content.invoice.title:"a product"}function I(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{asPlainText:d,asTextWithSpoilers:a}=n;if(d)return(0,o.MK)(e,t,void 0,g);const i=(0,u.e)(e,t,void 0,void 0,g);return a?r.ZP.createElement("span",null,i):r.ZP.createElement(h,{className:"action-link",message:t},i)}function w(e,t){return r.ZP.createElement(p,{groupCall:e},t)}function C(e,t){const n=(0,d.Z)((0,o.Js)(e),g);return t?n:r.ZP.createElement(f,{className:"action-link",sender:e},e&&(0,i.Z)(n))}function S(e,t,n){const a=(0,d.Z)((0,o.U)(e,t),g);return n?a:r.ZP.createElement(m,{className:"action-link",chatId:t.id},t&&(0,i.Z)(a))}function E(e,t){const n="another chat";return t?n:r.ZP.createElement(m,{className:"action-link",chatId:e},n)}function P(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,{X:()=>i,e:()=>s});var r=n(6137),o=n(5806),d=n(2340),a=n(8974),u=n(8035);function i(e,t,n,r,d){const{text:i,entities:s}=e.content.text||{};if(!i){const t=(0,o.UD)(e);return t?[(0,u.Z)(t,d)]:void 0}return(0,a.H)((0,u.Z)(i,d),s,t,n,void 0,e.id,r)}function s(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],a=arguments.length>3?arguments[3]:void 0,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:o.lN;const{entities:c}=t.content.text||{},l=null==c?void 0:c.some((e=>e.type===r.Vv.Spoiler));if(!l){const r=(0,u.Z)((0,o.MK)(e,t,n),s);return a?(0,d.Z)(r,["emoji","highlight"],{highlight:a}):(0,d.Z)(r)}const f=!n&&(0,o.Eb)(t),h=f?`${f} `:"",m=i(t,a,void 0,!0,s),p=(0,o.Kk)(e,t,m);return[h,...Array.isArray(p)?p:[p]].filter(Boolean)}},2340:(e,t,n)=>{n.d(t,{Z:()=>m});var r=n(4050),o=n(3681),d=n(3716),a=n(7361),u=n(4284),i=n(6752),s=n(782),c=n(7373),l=n(88);const f=/^[\d\wа-яё]$/i,h=/(\*\*|__).+?\1/g;function m(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["emoji"],n=arguments.length>2?arguments[2]:void 0;return"string"!=typeof e?[e]:(0,s.oA)(t.reduce(((e,t)=>{switch(t){case"escape_html":return p(e);case"hq_emoji":return o.Z.lastIndex=0,g(e,"big","jsx");case"emoji":return o.Z.lastIndex=0,g(e,"small","jsx");case"emoji_html":return o.Z.lastIndex=0,g(e,"small","html");case"br":return v(e,"jsx");case"br_html":return v(e,"html");case"highlight":return y(e,n.highlight);case"links":return I(e);case"simple_markdown":return w(e,"jsx");case"simple_markdown_html":return w(e,"html")}return e}),[e]))}function p(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)),[])}function g(e,t,n){return a.op?e:e.reduce(((e,d)=>{if("string"!=typeof d)return e.push(d),e;const a=(d=(0,u.g6)(d)).split(o.Z),s=d.match(o.Z)||[];return e.push(a[0]),s.reduce(((e,d,s)=>{const c=(0,u.U_)((0,o.l)(d));if(!c)return e;const l=(0,i.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*s+2;return a[f]&&e.push(a[f]),e}),e)}),[])}function v(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 a=n.trimLeft(),u=n.length-a.length;return e.push(String.fromCharCode(160).repeat(u)+a),o!==d.length-1&&e.push("jsx"===t?r.ZP.createElement("br",null):"
"),e}),[]);return[...e,...o]}),[])}function y(e,t){return e.reduce(((e,n)=>{if("string"!=typeof n||!t)return e.push(n),e;const o=n.toLowerCase(),d=o.indexOf(t.toLowerCase()),a=o[d+t.length];if(d<0||a&&a.match(f))return e.push(n),e;const u=[];return u.push(n.substring(0,d)),u.push(r.ZP.createElement("span",{className:"matching-text-highlight"},n.substring(d,d+t.length))),u.push(n.substring(d+t.length)),[...e,...u]}),[])}const b=new RegExp(`${d.FM}|${d.uW}`,"ig");function I(e){return e.reduce(((e,t)=>{if("string"!=typeof t)return e.push(t),e;const n=t.match(b);if(!n||!n.length)return e.push(t),e;const o=[];let d=n.shift(),a=0;for(;d;){const e=t.indexOf(d,a);o.push(t.substring(a,e)),d.startsWith("@")?o.push(r.ZP.createElement(c.Z,{username:d},d)):(d.endsWith("?")&&(d=d.slice(0,d.length-1)),o.push(r.ZP.createElement(l.Z,{text:d,url:d}))),a=e+d.length,d=n.shift()}return o.push(t.substring(a)),[...e,...o]}),[])}function w(e,t){return e.reduce(((e,n)=>{if("string"!=typeof n)return e.push(n),e;const o=n.split(h),d=n.match(h)||[];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 a=2*d+2;return o[a]&&e.push(o[a]),e}),e)}),[])}},8974:(e,t,n)=>{n.d(t,{z:()=>v,H:()=>g});var r=n(4050),o=n(3555),d=n(6137),a=n(2340),u=n(4319),i=n(711),s=n(7373),c=n(88),l=n(6752),f=n(706);const h=new Map,m=(0,l.y)("Spoiler"),p=(0,r.X$)((e=>{let{children:t,messageId:n}=e;const o=(0,r.sO)(null),[d,a,u]=(0,f.Z)(),i=(0,r.I4)((e=>{var t;e.preventDefault(),e.stopPropagation(),null===(t=h.get(n))||void 0===t||t.forEach((e=>e.reveal()));const r=o.current.innerText.length,d=1e3*Math.round(r/23),a=Math.max(5e3,Math.min(d,6e4));setTimeout((()=>{var e;null===(e=h.get(n))||void 0===e||e.forEach((e=>e.conceal())),u()}),a)}),[u,n]);return(0,r.d4)((()=>{if(n)return h.has(n)?h.get(n).push({reveal:a,conceal:u}):h.set(n,[{reveal:a,conceal:u}]),()=>{h.delete(n)}}),[u,i,d,n,a]),r.ZP.createElement("span",{className:m("&",!d&&"concealed",!d&&Boolean(n)&&"animated"),onClick:n&&!d?i:void 0},r.ZP.createElement("span",{className:m("content"),ref:o},t))}));function g(e,t,n,o,u,i,l){if(!t||!t.length)return y(e,n,o,u,l);const f=[];let h=!1;const m=function(e){const t=new Set,n=[];return e.forEach(((r,o)=>{if(t.has(o))return;const d=b(r,o,e,t);d&&(d.organizedIndexes.forEach((e=>{t.add(e)})),n.push(d))})),n}(t);function g(t,f,m,v){const b=[],{entity:E,nestedEntities:P}=m,{offset:M,length:A,type:k}=E;let T=e.substring(t,M);const N=T.length;T&&(h&&T.length>0&&"\n"===T[0]&&(T=T.substr(1),h=!1),T&&b.push(...y(T,n,o,u,l)));const L=t+N,R=L+A;let x=e.substring(M,M+A);const B=[];if(h&&x.length>0&&"\n"===x[0]&&(x=x.substr(1),h=!1),k===d.Vv.Pre&&(h=!0),P.length){let e=L;P.forEach(((t,n)=>{const{renderResult:r,entityEndIndex:o}=g(e,R,t,n===P.length-1);B.push(...r),e=o}))}const F=u?function(e,t,n){const r="string"==typeof t&&t,o=n.length?n.join(""):(0,a.Z)(t,["escape_html","emoji_html","br_html"]).join("");if(!r)return o;switch(e.type){case d.Vv.Bold:return`${o}`;case d.Vv.Italic:return`${o}`;case d.Vv.Underline:return`${o}`;case d.Vv.Code:return`${o}`;case d.Vv.Pre:return`\`\`\`
${o}
\`\`\``;case d.Vv.Strike:return`${o}`;case d.Vv.MentionName:return`${o}`;case d.Vv.Url:case d.Vv.TextUrl:return`${o}`;case d.Vv.Spoiler:return`${o}
`;default:return o}}(E,x,B):function(e,t,n,o,a,u){const i="string"==typeof t&&t,l=n.length?n:t;function f(){return y(l,o,void 0,void 0,u)}if(!i)return f();if(u){const t=f();return e.type===d.Vv.Spoiler?r.ZP.createElement(p,null,t):t}switch(e.type){case d.Vv.Bold:return r.ZP.createElement("strong",null,f());case d.Vv.Blockquote:return r.ZP.createElement("blockquote",null,f());case d.Vv.BotCommand:return r.ZP.createElement("a",{onClick:w,className:"text-entity-link",dir:"auto"},f());case d.Vv.Hashtag:case d.Vv.Cashtag:return r.ZP.createElement("a",{onClick:C,className:"text-entity-link",dir:"auto"},f());case d.Vv.Code:return r.ZP.createElement("code",{className:"text-entity-code",onClick:S,role:"textbox",tabIndex:0},f());case d.Vv.Email:return r.ZP.createElement("a",{href:`mailto:${i}`,target:"_blank",rel:"noopener noreferrer",className:"text-entity-link",dir:"auto"},f());case d.Vv.Italic:return r.ZP.createElement("em",null,f());case d.Vv.MentionName:return r.ZP.createElement(s.Z,{userId:e.userId},f());case d.Vv.Mention:return r.ZP.createElement(s.Z,{username:i},f());case d.Vv.Phone:return r.ZP.createElement("a",{href:`tel:${i}`,className:"text-entity-link",dir:"auto"},f());case d.Vv.Pre:return r.ZP.createElement("pre",{className:"text-entity-pre"},f());case d.Vv.Strike:return r.ZP.createElement("del",null,f());case d.Vv.TextUrl:case d.Vv.Url:return r.ZP.createElement(c.Z,{url:I(i,e),text:i},f());case d.Vv.Underline:return r.ZP.createElement("ins",null,f());case d.Vv.Spoiler:return r.ZP.createElement(p,{messageId:a},f());default:return f()}}(E,x,B,n,i,l);if(Array.isArray(F)?b.push(...F):b.push(F),v&&R0&&"\n"===t[0]&&(t=t.substring(1)),t&&b.push(...y(t,n,o,u,l))}return{renderResult:b,entityEndIndex:R}}let v=0;return m.forEach(((t,n)=>{const{renderResult:r,entityEndIndex:o}=g(v,e.length,t,n===m.length-1);f.push(...r),v=o})),f}function v(e){const{text:t,entities:n}=e||{};if(!t)return"";const r=g(t,n,void 0,void 0,!0);return Array.isArray(r)?r.join(""):r}function y(e,t,n,r,o){if(Array.isArray(e)){const d=[];return e.forEach((e=>{d.push(...y(e,t,n,r,o))})),d}if(r)return(0,a.Z)(e,["escape_html","emoji_html","br_html"]);const d=[n?"hq_emoji":"emoji"];return o||d.push("br"),t?(0,a.Z)(e,d.concat("highlight"),{highlight:t}):(0,a.Z)(e,d)}function b(e,t,n,r){const{offset:o,length:d}=e,a=new Set([t]);if(r.has(t))return;const u=[];return n.filter(((e,n)=>n>t&&e.offset>=o&&e.offsetb(e,n.indexOf(e),n,r))).filter(Boolean).forEach((e=>{let t=!1;e.organizedIndexes.forEach((e=>{t||a.has(e)||(t=!0),a.add(e)})),t&&u.push(e)})),{entity:e,organizedIndexes:a,nestedEntities:u}}function I(e,t){const{type:n,url:r}=t;return n===d.Vv.TextUrl&&r?r:e}function w(e){(0,o.Sv)().sendBotCommand({command:e.currentTarget.innerText})}function C(e){(0,o.Sv)().setLocalTextSearchQuery({query:e.currentTarget.innerText}),(0,o.Sv)().searchTextMessagesLocal()}function S(e){(0,u.TE)(e.currentTarget.innerText),(0,o.Sv)().showNotification({message:(0,i.i0)("TextCopied")})}},386:(e,t,n)=>{n.d(t,{b:()=>a,q:()=>d});var r=n(3716),o=n(7361);function d(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];o.cj||!document.activeElement||document.activeElement.id!==r.R2||!t&&e.target!==e.currentTarget||e.preventDefault()}function a(e){d(e,!0)}},7373:(e,t,n)=>{n.d(t,{Z:()=>a});var r=n(4050),o=n(3555),d=n(1192);const a=(0,o.c$)(((e,t)=>{let{userId:n}=t;return{userOrChat:n?(0,d.dy)(e,n):void 0}}))((e=>{let{username:t,userOrChat:n,children:d}=e;const{openChat:a,openChatByUsername:u}=(0,o.Sv)();return r.ZP.createElement("a",{onClick:()=>{n?a({id:n.id}):t&&u({username:t.substring(1)})},className:"text-entity-link",dir:"auto"},d)}))},231:(e,t,n)=>{n.d(t,{Z:()=>u});var r=n(4050),o=n(6752),d=n(9204),a=n(8512);const u=e=>{let{ref:t,type:n="button",id:u,onClick:i,onContextMenu:s,onMouseDown:c,onMouseEnter:l,onMouseLeave:f,onFocus:h,children:m,size:p="default",color:g="primary",backgroundImage:v,className:y,round:b,pill:I,fluid:w,isText:C,isLoading:S,ariaLabel:E,ariaControls:P,hasPopup:M,href:A,download:k,disabled:T,ripple:N,faded:L,tabIndex:R,isRtl:x,withClickPropagation:B}=e,F=(0,r.sO)(null);t&&(F=t);const[O,D]=(0,r.eJ)(!1),Z=(0,o.Z)("Button",y,p,g,b&&"round",I&&"pill",w&&"fluid",T&&"disabled",C&&"text",S&&"loading",N&&"has-ripple",L&&"faded",O&&"clicked",v&&"with-image"),_=(0,r.I4)((e=>{!T&&i&&i(e),D(!0),setTimeout((()=>{D(!1)}),400)}),[T,i]),$=(0,r.I4)((e=>{B||e.preventDefault(),!T&&c&&c(e)}),[c,T,B]);return A?r.ZP.createElement("a",{ref:F,id:u,className:Z,href:A,title:E,download:k,tabIndex:R,dir:x?"rtl":void 0,"aria-label":E,"aria-controls":P},m,!T&&N&&r.ZP.createElement(a.Z,null)):r.ZP.createElement("button",{ref:F,id:u,type:n,className:Z,onClick:_,onContextMenu:s,onMouseDown:$,onMouseEnter:l&&!T?l:void 0,onMouseLeave:f&&!T?f:void 0,onFocus:h&&!T?h:void 0,"aria-label":E,"aria-controls":P,"aria-haspopup":M,title:E,tabIndex:R,dir:x?"rtl":void 0,style:v?`background-image: url(${v})`:void 0},S?r.ZP.createElement("div",null,r.ZP.createElement("span",{dir:x?"auto":void 0},"Please wait..."),r.ZP.createElement(d.Z,{color:C?"blue":"white"})):m,!T&&N&&r.ZP.createElement(a.Z,null))}},4605:(e,t,n)=>{n.d(t,{Z:()=>i});var r=n(4050),o=n(6752),d=n(9107),a=n(2340),u=n(9204);const i=(0,r.X$)((e=>{let{id:t,name:n,value:i,label:s,subLabel:c,checked:l,tabIndex:f,disabled:h,round:m,blocking:p,isLoading:g,onChange:v,onCheck:y}=e;const b=(0,d.Z)(),I=(0,r.I4)((e=>{v&&v(e),y&&y(e.currentTarget.checked)}),[v,y]),w=(0,o.Z)("Checkbox",h&&"disabled",m&&"round",g&&"loading",p&&"blocking");return r.ZP.createElement("label",{className:w,dir:b.isRtl?"rtl":void 0},r.ZP.createElement("input",{type:"checkbox",id:t,name:n,value:i,checked:l,disabled:h,tabIndex:f,onChange:I}),r.ZP.createElement("div",{className:"Checkbox-main"},r.ZP.createElement("span",{className:"label",dir:"auto"},(0,a.Z)(s)),c&&r.ZP.createElement("span",{className:"subLabel",dir:"auto"},(0,a.Z)(c))),g&&r.ZP.createElement(u.Z,null))}))},3106:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(2328);const d=e=>{let{trigger:t,className:n,children:d,positionX:a="left",positionY:u="top",footer:i,forceOpen:s,onOpen:c,onClose:l}=e;const f=(0,r.sO)(null),h=(0,r.sO)(null),[m,p]=(0,r.eJ)(!1);return r.ZP.createElement("div",{ref:h,className:`DropdownMenu ${n||""}`,onKeyDown:e=>{const t=f.current;if(!m||40!==e.keyCode||!t)return;const n=document.activeElement,r=Array.from(t.children);n&&-1!==r.indexOf(n)||r[0].focus()}},t({onTrigger:()=>{p(!m),m?l&&l():c&&c()},isOpen:m}),r.ZP.createElement(o.Z,{ref:f,containerRef:h,isOpen:m||Boolean(s),className:n||"",positionX:a,positionY:u,footer:i,autoClose:!0,onClose:()=>{p(!1),l&&l()},shouldSkipTransition:s},d))}},7687:(e,t,n)=>{n.d(t,{Z:()=>a});var r=n(4050),o=n(6752),d=n(9107);const a=(0,r.X$)((e=>{let{ref:t,id:n,className:a,value:u,label:i,error:s,success:c,disabled:l,readOnly:f,placeholder:h,autoComplete:m,inputMode:p,maxLength:g,tabIndex:v,onChange:y,onInput:b,onKeyPress:I,onKeyDown:w,onBlur:C,onPaste:S}=e;const E=(0,d.Z)(),P=s||c||i,M=(0,o.Z)("input-group",u&&"touched",s?"error":c&&"success",l&&"disabled",f&&"disabled",P&&"with-label",a);return r.ZP.createElement("div",{className:M,dir:E.isRtl?"rtl":void 0},r.ZP.createElement("input",{ref:t,className:"form-control",type:"text",id:n,dir:"auto",value:u||"",tabIndex:v,placeholder:h,maxLength:g,autoComplete:m,inputMode:p,disabled:l,readOnly:f,onChange:y,onInput:b,onKeyPress:I,onKeyDown:w,onBlur:C,onPaste:S,"aria-label":P}),P&&r.ZP.createElement("label",{htmlFor:n},P))}))},8033:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(6752);const d=e=>{let{children:t,className:n,isRtl:d,onClick:a}=e;const u=(0,r.I4)((e=>{e.preventDefault(),a(e)}),[a]);return r.ZP.createElement("a",{href:"#",className:(0,o.Z)("Link",n),dir:d?"rtl":"auto",onClick:a?u:void 0},t)}},4288:(e,t,n)=>{n.d(t,{Z:()=>a});var r=n(4050),o=n(9204),d=n(6752);const a=(0,r.X$)((e=>{let{color:t="blue",backgroundColor:n,onClick:a}=e;return r.ZP.createElement("div",{className:(0,d.Z)("Loading",a&&"interactive"),onClick:a},r.ZP.createElement(o.Z,{color:t,backgroundColor:n}))}))},2328:(e,t,n)=>{n.d(t,{Z:()=>m});var r=n(4050),o=n(1212),d=n(2313),a=n(8758),u=n(274),i=n(3989),s=n(6752),c=n(8674),l=n(6590),f=n(386),h=n(7361);const m=e=>{let{ref:t,containerRef:n,isOpen:m,id:p,className:g,style:v,bubbleStyle:y,ariaLabelledBy:b,children:I,transformOriginX:w,transformOriginY:C,positionX:S="left",positionY:E="top",autoClose:P=!1,footer:M,noCloseOnBackdrop:A=!1,noCompact:k,onCloseAnimationEnd:T,onClose:N,onMouseEnter:L,onMouseLeave:R,shouldSkipTransition:x}=e,B=(0,r.sO)(null);t&&(B=t);const F=n||B,{transitionClassNames:O}=(0,o.Z)(m,T,x,void 0,x);(0,r.d4)((()=>m&&N?(0,i.Z)(N):void 0),[m,N]),(0,l.ZP)(m,N,void 0,void 0,P),(0,u.Z)((e=>{let[t]=e;(m||!m&&!0===t)&&(0,c.YW)(200)}),[m]);const D=(0,d.Z)(B,m,P?N:void 0,void 0,!0);(0,a.Z)(m,F,A?void 0:N);const Z=(0,s.Z)("bubble menu-container custom-scroll",E,S,M&&"with-footer",O),_=void 0!==C?`${C}px`:void 0,$=void 0!==w?`${w}px`:void 0;return r.ZP.createElement("div",{id:p,className:(0,s.Z)("Menu no-selection",!k&&h.FW&&"compact",!h.gk&&"no-blur",g),style:v,"aria-labelledby":b,role:b?"menu":void 0,onKeyDown:m?D:void 0,onMouseEnter:L,onMouseLeave:m?R:void 0},m&&r.ZP.createElement("div",{className:"backdrop",onMouseDown:f.b}),r.ZP.createElement("div",{ref:B,className:Z,style:`transform-origin: ${$||S} ${_||E};${y||""}`,onClick:P?N:void 0},I,M&&r.ZP.createElement("div",{className:"footer"},M)))}},8964:(e,t,n)=>{n.d(t,{Z:()=>u});var r=n(4050),o=n(6752),d=n(9107),a=n(7361);const u=e=>{const{icon:t,className:n,children:u,onClick:i,href:s,download:c,disabled:l,destructive:f,ariaLabel:h}=e,m=(0,d.Z)(),p=(0,r.I4)((e=>{if(l||!i)return e.stopPropagation(),void e.preventDefault();i(e)}),[l,i]),g=(0,r.I4)((e=>{if(13===e.keyCode||32===e.keyCode)return l||!i?(e.stopPropagation(),void e.preventDefault()):void i(e)}),[l,i]),v=(0,o.Z)("MenuItem",n,l&&"disabled",f&&"destructive",a.FW&&"compact"),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:v,href:s,download:c,"aria-label":h,title:h,target:s.startsWith(window.location.origin)?"_self":"_blank",rel:"noopener noreferrer",dir:m.isRtl?"rtl":void 0,onClick:i},y):r.ZP.createElement("div",{role:"button",tabIndex:0,className:v,onClick:p,onKeyDown:g,"aria-label":h,title:h,dir:m.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(),a=o.offsetWidth/2;t([...e,{x:r.clientX-d.x-a/2,y:r.clientY-d.y-a/2,size:a}]),requestAnimationFrame((()=>{n()}))}),[e,n]);return r.ZP.createElement("div",{className:"ripple-container",onMouseDown:d},e.map((e=>{let{x:t,y:n,size:o}=e;return r.ZP.createElement("span",{style:`left: ${t}px; top: ${n}px; width: ${o}px; height: ${o}px;`})})))}))},9204:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(6752);const d=e=>{let{color:t="blue",backgroundColor:n}=e;return r.ZP.createElement("div",{className:(0,o.Z)("Spinner",t,n&&"with-background",`bg-${n}`)},r.ZP.createElement("div",null))}},3716:(e,t,n)=>{n.d(t,{$E:()=>ke,$O:()=>qe,AE:()=>ae,AJ:()=>ue,AR:()=>z,Bg:()=>Ye,CX:()=>W,Cg:()=>u,Cy:()=>b,DC:()=>be,DU:()=>He,Db:()=>Xe,EG:()=>ze,EN:()=>x,FD:()=>Ue,FM:()=>De,FS:()=>$e,FV:()=>Ve,Hk:()=>F,It:()=>nt,Ji:()=>o,K2:()=>Ce,K7:()=>he,LH:()=>ut,Mw:()=>ye,Nf:()=>We,Ng:()=>Re,Ov:()=>R,PM:()=>Me,Q:()=>ve,QU:()=>X,Qx:()=>$,R2:()=>q,Rk:()=>y,Ro:()=>dt,S:()=>i,SG:()=>w,Ti:()=>s,Uh:()=>p,V$:()=>se,VC:()=>Oe,Vk:()=>O,Vv:()=>rt,Vx:()=>h,WS:()=>Ge,Y:()=>Le,Y7:()=>Ie,YQ:()=>T,ZT:()=>a,_m:()=>te,aC:()=>at,aw:()=>je,b6:()=>H,bK:()=>ce,bM:()=>Se,b_:()=>f,by:()=>P,ck:()=>le,dI:()=>Fe,eA:()=>l,eM:()=>d,ee:()=>E,fK:()=>ie,fo:()=>S,g:()=>ot,g$:()=>_e,gJ:()=>v,hT:()=>k,iC:()=>r,jT:()=>ee,jV:()=>Ae,kU:()=>Ne,ks:()=>ne,ku:()=>Ee,l3:()=>re,lF:()=>C,lO:()=>g,lW:()=>I,lo:()=>A,mU:()=>et,mo:()=>D,mw:()=>U,nY:()=>Y,oB:()=>j,oG:()=>xe,o_:()=>J,ou:()=>c,p3:()=>tt,pR:()=>Te,pn:()=>B,qU:()=>Z,qp:()=>ge,rO:()=>de,rS:()=>N,r_:()=>K,s2:()=>Q,sR:()=>Je,sd:()=>m,t4:()=>Ke,t_:()=>L,uW:()=>Ze,u_:()=>oe,ul:()=>_,vi:()=>Qe,w7:()=>me,wG:()=>Be,xS:()=>G,xn:()=>fe,yK:()=>we,z7:()=>pe,zq:()=>Pe,zy:()=>V});const r="Telegram WebZ",o="1.38.2",d=!1,a=!1,u=!1,i="Shoot!\nSomething went wrong, please see the error details in Dev Tools Console.",s="Telegram",c=" [Inactive]",l=!1,f="user_auth",h="GramJs:sessionId",m=!1,p="tt-global-state",g=500,v=200,y=30,b=!1,I="tt-media",w="tt-media-avatars",C="tt-media-progressive",S="tt-custom-bg",E="tt-lang-packs-v8",P=[1,5,10,50,100,500],M="undefined"!=typeof window&&window.innerHeight>=900,A=1,k=M?60:40,T=2*k,N=72,L=M?30:25,R=100,x=42,B=42,F=20,O=30,D=200,Z=500,_=20,$=1,U=1,j=0,V=2,W=V,G=16,H=17,z=15,K=1e4,J=3e3,q="editable-message-text",Y="editable-message-text-modal",Q="data-has-custom-appendix",X=1440,ee=1150,te=1275,ne=925,re=600,oe=950,de=450,ae=1e9,ue="0",ie=100,se=1500,ce=250,le=600,fe=500,he=(Math.round((ce+le)/2),new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),13),me=11,pe=160,ge=120,ve=64,ye=48,be=32,Ie=64,we=64,Ce=160,Se=140,Ee=100,Pe=100,Me=140,Ae=140,ke="NO_STICKER_SET",Te="en",Ne=200,Le=450,Re="video/quicktime",xe=new Set(["image/png","image/gif","image/jpeg"]),Be=new Set(["video/mp4"]),Fe=new Set([...xe,...Be]),Oe="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()@:%_+.~#?&/=]*)",Ze="(@[\\w\\d_-]+)",_e=/^tg:(\/\/)?([?=&\d\w_-]+)?/gm,$e=/^(?:https?:\/\/)?(?:t\.me\/)/gm,Ue=new Set(["AU","BD","CA","CO","EG","HN","IE","IN","JO","MX","MY","NI","NZ","PH","PK","SA","SV","US"]),je="777000",Ve="1271266957",We=0,Ge=1,He=10,ze=5,Ke=2147483646,Je="en",qe="android",Ye=["android","ios","tdesktop","macos"],Qe="TelegramTips",Xe=["ar","pt-br","id","it","ko","ms","pl","es","tr"],et="https://bugs.telegram.org/?tag_ids=41&sort=time",tt="#A2AF8E",nt="#0F0F0F",rt="#0a0a0a8c",ot="rgba(90, 110, 70, 0.6)",dt=100,at=100*dt,ut=!1},5456:(e,t,n)=>{var r=n(3555),o=n(1226),d=n(3716),a=n(7361),u=n(8406),i=n(9524),s=n(7358),c=n(3100),l=n(1622);(0,r.iw)("initApi",(async(e,t)=>{d.Cg||(await(0,c.Qw)(),(0,c.f3)()),(0,o.g8)(t.apiUpdate,{userAgent:navigator.userAgent,platform:a.Lt,sessionData:(0,c.K8)(),isTest:window.location.search.includes("test"),isMovSupported:a.pA,isWebmSupported:a.Hh})})),(0,r.iw)("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.iw)("setAuthCode",((e,t,n)=>{const{code:r}=n;return(0,o.t9)("provideAuthCode",r),{...e,authIsLoading:!0,authError:void 0}})),(0,r.iw)("setAuthPassword",((e,t,n)=>{const{password:r}=n;return(0,o.t9)("provideAuthPassword",r),{...e,authIsLoading:!0,authError:void 0}})),(0,r.iw)("uploadProfilePhoto",((e,t,n)=>{const{file:r}=n;(0,o.t9)("uploadProfilePhoto",r)})),(0,r.iw)("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.iw)("returnToAuthPhoneNumber",(e=>((0,o.t9)("restartAuth"),{...e,authError:void 0}))),(0,r.iw)("goToAuthQrCode",(e=>((0,o.t9)("restartAuthWithQr"),{...e,authIsLoadingQrCode:!0,authError:void 0}))),(0,r.iw)("saveSession",((e,t,n)=>{const{sessionData:r}=n;r?(0,c.wX)(n.sessionData,e.currentUserId):(0,c.jv)()})),(0,r.iw)("signOut",(async(e,t,n)=>{try{await(0,u.r1)(),await(0,o.t9)("destroy"),await(0,l.IT)(!1)}catch(e){}(0,r.Sv)().reset(),null!=n&&n.forceInitApi&&(0,r.Sv)().initApi()})),(0,r.iw)("reset",(()=>{(0,c.jv)(),i.clear(d.lW),i.clear(d.SG),i.clear(d.lF),i.clear(d.fo);const e=d.ee.replace(/\d+$/,""),t=(d.ee.match(/\d+$/)||[0])[0];for(let n=0;n{(0,o.t9)("disconnect")})),(0,r.iw)("loadNearestCountry",(async e=>{if("connectionStateReady"!==e.connectionState)return;const t=await(0,o.t9)("fetchNearestCountry");return{...(0,r.Rd)(),authNearestCountry:t}})),(0,r.iw)("setDeviceToken",((e,t,n)=>({...e,push:{deviceToken:n,subscribedAt:Date.now()}}))),(0,r.iw)("deleteDeviceToken",(e=>({...e,push:void 0})))},1371:(e,t,n)=>{var r=n(3555),o=n(1713),d=n(3716),a=n(1226),u=n(782),i=n(8406),s=n(711),c=n(1192),l=n(5406),f=n(5806);function h(e,t){let{visibility:n,allowedIds:r,deniedIds:o}=t;const{users:{byId:d},chats:{byId:a}}=e,u={visibility:n};let i,s;const c=e=>{if(!(0,f.YC)(e))return;const{id:t,accessHash:n}=d[e]||{};return t?{id:t,accessHash:n}:void 0},l=e=>{if((0,f.YC)(e))return;const t=a[e];return t?{id:t.id}:void 0};return"contacts"!==n&&"nobody"!==n||(i=r.map(c).filter(Boolean),s=r.map(l).filter(Boolean),i.length>0&&(u.allowedUsers=i),s.length>0&&(u.allowedChats=s)),"everybody"!==n&&"contacts"!==n||(i=o.map(c).filter(Boolean),s=o.map(l).filter(Boolean),i.length>0&&(u.blockedUsers=i),s.length>0&&(u.blockedChats=s)),u}(0,r.iw)("updateProfile",(async(e,t,n)=>{const{photo:d,firstName:u,lastName:i,bio:s,username:f}=n,{currentUserId:h}=e;if(h){if((0,r.R3)({...(0,r.Rd)(),profileEdit:{progress:o.rN.InProgress}}),d&&await(0,a.t9)("updateProfilePhoto",d),(u||i||s)&&await(0,a.t9)("updateProfile",{firstName:u,lastName:i,about:s})){e=(0,r.Rd)();const t=h&&(0,c.dy)(e,h);t&&(0,r.R3)((0,l.Nq)(e,t.id,{firstName:u,lastName:i,fullInfo:{...t.fullInfo,bio:s}}))}return f&&await(0,a.t9)("updateUsername",f)&&h&&(0,r.R3)((0,l.Nq)((0,r.Rd)(),h,{username:f})),{...(0,r.Rd)(),profileEdit:{progress:o.rN.Complete}}}})),(0,r.iw)("checkUsername",(async(e,t,n)=>{const{username:d}=n;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 u=await(0,a.t9)("checkUsername",d);return e=(0,r.Rd)(),{...e,profileEdit:{...e.profileEdit,isUsernameAvailable:u}}})),(0,r.iw)("loadWallpapers",(async()=>{const e=await(0,a.t9)("fetchWallpapers");if(!e)return;const t=(0,r.Rd)();return{...t,settings:{...t.settings,loadedWallpapers:e.wallpapers}}})),(0,r.iw)("uploadWallpaper",(async(e,t,n)=>{const d=n,u=URL.createObjectURL(d);(0,r.R3)({...e,settings:{...e.settings,loadedWallpapers:[{slug:o.mp,document:{fileName:"",size:d.size,mimeType:d.type,previewBlobUrl:u}},...e.settings.loadedWallpapers||[]]}});const i=await(0,a.t9)("uploadWallpaper",d);if(!i)return;const{wallpaper:s}=i;if(!(e=(0,r.Rd)()).settings.loadedWallpapers)return;const c=e.settings.loadedWallpapers[0];if(!c||c.slug!==o.mp)return;const l={...s,document:{...s.document,previewBlobUrl:u}};return{...e,settings:{...e.settings,loadedWallpapers:[l,...e.settings.loadedWallpapers.slice(1)]}}})),(0,r.iw)("loadBlockedContacts",(async e=>{var t,n;const o=await(0,a.t9)("fetchBlockedContacts");if(o)return e=(0,r.Rd)(),null!==(t=o.users)&&void 0!==t&&t.length&&(e=(0,l.Sh)(e,(0,u.ee)(o.users,"id"))),null!==(n=o.chats)&&void 0!==n&&n.length&&(e=(0,l.GL)(e,(0,u.ee)(o.chats,"id"))),{...e,blocked:{...e.blocked,ids:[...e.blocked.ids||[],...o.blockedIds],totalCount:o.totalCount}}})),(0,r.iw)("blockContact",(async(e,t,n)=>{const{contactId:o,accessHash:d}=n;if(await(0,a.t9)("blockContact",o,d))return(0,l.O4)((0,r.Rd)(),o)})),(0,r.iw)("unblockContact",(async(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}if(await(0,a.t9)("unblockContact",o,d))return(0,l.rB)((0,r.Rd)(),o)})),(0,r.iw)("loadAuthorizations",(async()=>{const e=await(0,a.t9)("fetchAuthorizations");if(e)return{...(0,r.Rd)(),activeSessions:e}})),(0,r.iw)("terminateAuthorization",(async(e,t,n)=>{const{hash:o}=n;if(await(0,a.t9)("terminateAuthorization",o))return e=(0,r.Rd)(),{...e,activeSessions:e.activeSessions.filter((e=>e.hash!==o))}})),(0,r.iw)("terminateAllAuthorizations",(async e=>{if(await(0,a.t9)("terminateAllAuthorizations"))return e=(0,r.Rd)(),{...e,activeSessions:e.activeSessions.filter((e=>e.isCurrent))}})),(0,r.iw)("loadNotificationExceptions",(async e=>{const{serverTimeOffset:t}=e,n=await(0,a.t9)("fetchNotificationExceptions",{serverTimeOffset:t});if(n)return(0,l.aJ)((0,r.Rd)(),n)})),(0,r.iw)("loadNotificationSettings",(async e=>{const{serverTimeOffset:t}=e,n=await(0,a.t9)("fetchNotificationSettings",{serverTimeOffset:t});if(n)return(0,l.BI)((0,r.Rd)(),n)})),(0,r.iw)("updateNotificationSettings",(async(e,t,n)=>{const{peerType:o,isSilent:d,shouldShowPreviews:u}=n;if(await(0,a.t9)("updateNotificationSettings",o,{isSilent:d,shouldShowPreviews:u}))return(0,l.HN)((0,r.Rd)(),o,d,u)})),(0,r.iw)("updateWebNotificationSettings",((e,t,n)=>{(0,r.R3)((0,l.BI)(e,n));const{hasPushNotifications:o,hasWebNotifications:d}=e.settings.byKey;d&&o?(0,i.Ld)():(0,i.r1)()})),(0,r.iw)("updateContactSignUpNotification",(async(e,t,n)=>{const{isSilent:o}=n;if(await(0,a.t9)("updateContactSignUpNotification",o))return(0,l.BI)((0,r.Rd)(),{hasContactJoinedNotifications:!o})})),(0,r.iw)("loadLanguages",(async()=>{const e=await(0,a.t9)("fetchLanguages");if(e)return(0,l.BI)((0,r.Rd)(),{languages:e})})),(0,r.iw)("loadPrivacySettings",(async e=>{const[t,n,o,d,u]=await Promise.all([(0,a.t9)("fetchPrivacySettings","phoneNumber"),(0,a.t9)("fetchPrivacySettings","lastSeen"),(0,a.t9)("fetchPrivacySettings","profilePhoto"),(0,a.t9)("fetchPrivacySettings","forwards"),(0,a.t9)("fetchPrivacySettings","chatInvite")]);if(t&&n&&o&&d&&u)return(e=(0,r.Rd)()).settings.privacy.phoneNumber=t,e.settings.privacy.lastSeen=n,e.settings.privacy.profilePhoto=o,e.settings.privacy.forwards=d,e.settings.privacy.chatInvite=u,e})),(0,r.iw)("setPrivacyVisibility",(async(e,t,n)=>{const{privacyKey:o,visibility:d}=n,{privacy:{[o]:u}}=e.settings;if(!u)return;const i=h(e,{visibility:d,allowedIds:[...u.allowUserIds,...u.allowChatIds],deniedIds:[...u.blockUserIds,...u.blockChatIds]}),s=await(0,a.t9)("setPrivacySettings",o,i);return s?(e=(0,r.Rd)(),{...e,settings:{...e.settings,privacy:{...e.settings.privacy,[o]:s}}}):void 0})),(0,r.iw)("setPrivacySettings",(async(e,t,n)=>{const{privacyKey:o,isAllowList:d,contactsIds:u}=n,{privacy:{[o]:i}}=e.settings;if(!i)return;const s=h(e,{visibility:i.visibility,allowedIds:d?u:[...i.allowUserIds,...i.allowChatIds],deniedIds:d?[...i.blockUserIds,...i.blockChatIds]:u}),c=await(0,a.t9)("setPrivacySettings",o,s);return c?(e=(0,r.Rd)(),{...e,settings:{...e.settings,privacy:{...e.settings.privacy,[o]:c}}}):void 0})),(0,r.iw)("updateIsOnline",((e,t,n)=>{(0,a.t9)("updateIsOnline",n)})),(0,r.iw)("loadContentSettings",(async()=>{const e=await(0,a.t9)("fetchContentSettings");if(e)return(0,l.BI)((0,r.Rd)(),e)})),(0,r.iw)("updateContentSettings",(async(e,t,n)=>{if((0,r.R3)((0,l.BI)((0,r.Rd)(),{isSensitiveEnabled:n})),!await(0,a.t9)("updateContentSettings",n))return(0,l.BI)((0,r.Rd)(),{isSensitiveEnabled:!n})})),(0,r.iw)("loadCountryList",(async function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{langCode:o}=n;o||(o=e.settings.byKey.language);const d=await(0,a.t9)("fetchCountryList",{langCode:o});if(d)return{...(0,r.Rd)(),countryList:d}})),(0,r.iw)("ensureTimeFormat",(async(e,t)=>{if(e.authNearestCountry){const n=d.FD.has(e.authNearestCountry.toUpperCase())?"12h":"24h";t.setSettingOption({timeFormat:n}),(0,s.qf)(n)}if(e.settings.byKey.wasTimeFormatSetManually)return;const n=await(0,a.t9)("fetchNearestCountry");if(n){const e=d.FD.has(n.toUpperCase())?"12h":"24h";t.setSettingOption({timeFormat:e}),(0,s.qf)(e)}})),(0,r.iw)("loadAppConfig",(async()=>{const e=await(0,a.t9)("fetchAppConfig");if(e)return{...(0,r.Rd)(),appConfig:e}}))},8304:(e,t,n)=>{var r=n(3555),o=n(3716),d=n(8406),a=n(5406),u=n(711),i=n(1192),s=n(1622),c=n(1947);(0,r.iw)("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,i.dZ)(e);t&&n&&(0,d.Ld)(),(0,u.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,s.IT)(!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,s.IT)(!0),(0,r.R3)({...t,isLoggingOut:!1})}}(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)();if(t!==n.connectionState&&((0,r.R3)({...n,connectionState:t}),"connectionStateBroken"===t)){const e=!n.authState||["authorizationStateWaitPhoneNumber","authorizationStateWaitCode","authorizationStateWaitPassword","authorizationStateWaitRegistration","authorizationStateWaitQrCode"].includes(n.authState);(0,r.Sv)().signOut({forceInitApi:e})}}(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.Sv)().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,a.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}}}))},9005:(e,t,n)=>{var r=n(3555),o=n(3716),d=n(7361),a=n(711),u=n(7370),i=n(1192),s=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,i.Pu)(n),{animationLevel:a}=n.settings.byKey;d!==t&&((0,u.Z)(d,a===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.iw)("init",(e=>{const{animationLevel:t,messageTextSize:n,language:r}=e.settings.byKey,l=(0,i.Pu)(e);(0,a.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,u.Z)(l,t===o.zy),(0,c.$)(),(0,s.px)(),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.iw)("setIsUiReady",((e,t,n)=>{const{uiReadyState:r}=n;return 2===r&&document.body.classList.remove("initial"),{...e,uiReadyState:r}})),(0,r.iw)("setAuthPhoneNumber",((e,t,n)=>{const{phoneNumber:r}=n;return{...e,authPhoneNumber:r}})),(0,r.iw)("setAuthRememberMe",((e,t,n)=>({...e,authRememberMe:Boolean(n)}))),(0,r.iw)("clearAuthError",(e=>({...e,authError:void 0}))),(0,r.iw)("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})}))},3456:(e,t,n)=>{var r=n(3555),o=n(5406);(0,r.iw)("setSettingOption",((e,t,n)=>(0,o.BI)(e,n))),(0,r.iw)("setThemeSettings",((e,t,n)=>{const{theme:r,...d}=n;return(0,o.lr)(e,r,d)}))},2825:(e,t,n)=>{n.d(t,{$l:()=>$,Bf:()=>h,G9:()=>m,GM:()=>C,H5:()=>N,Hd:()=>R,Hp:()=>P,Mg:()=>k,Nl:()=>M,Qm:()=>T,RT:()=>E,Ru:()=>v,SB:()=>D,Sm:()=>F,U:()=>w,VE:()=>A,YC:()=>f,ZV:()=>p,cc:()=>O,eA:()=>g,hu:()=>S,i4:()=>B,ih:()=>_,l6:()=>b,pE:()=>x,pK:()=>y,q8:()=>L,zF:()=>Z,zX:()=>I});var r=n(6137),o=n(3716),d=n(782),a=n(3311),u=n(790),i=n(5765);const s=Date.now()/1e3+31622400,c=3e9,l=3e8;function f(e){return"number"==typeof e?e>0:!e.startsWith("-")}function h(e){return m(e)||p(e)}function m(e){return"chatTypeBasicGroup"===e.type}function p(e){return"chatTypeSuperGroup"===e.type}function g(e){return"chatTypeChannel"===e.type}function v(e){return"chatTypePrivate"===e.type||"chatTypeBasicGroup"===e.type}function y(e){return e===o.FV}function b(e){switch(e.type){case"chatTypePrivate":return"PrivateChat";case"chatTypeBasicGroup":case"chatTypeSuperGroup":return"AccDescrGroup";case"chatTypeChannel":return"AccDescrChannel";default:return"Chat"}}function I(e){if("chatTypePrivate"===e.type||"chatTypeSecret"===e.type)return e.id}function w(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return r||n&&t.id===n.id&&n.isSelf?e("SavedMessages"):t.title||e("HiddenName")}function C(e){if(e.fullInfo)return e.fullInfo.about}function S(e){const{username:t}=e;if(t)return`https://t.me/${t}`;const{inviteLink:n}=e.fullInfo||{};return n}function E(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"normal";if(e.avatarHash)return"big"===t?`profile${e.id}?${e.avatarHash}`:`avatar${e.id}?${e.avatarHash}`}function P(e){return!e.lastMessage}function M(e){return Boolean(e.adminRights)}function A(e,t){return!!e.adminRights&&e.adminRights[t]}function k(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 T(e,t){return t!==r._f||!(e.isRestricted||e.migratedTo||e.isNotJoined||y(e.id))&&(!!e.isCreator||!!f(e.id)||(g(e)?A(e,"postMessages"):M(e)||!k(e,"sendMessages")))}function N(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!e)return{canAttachMedia:!1,canAttachPolls:!1,canSendStickers:!1,canSendGifs:!1,canAttachEmbedLinks:!1};const n=M(e);return{canAttachMedia:n||!k(e,"sendMedia"),canAttachPolls:(n||!k(e,"sendPolls"))&&(!f(e.id)||t),canSendStickers:n||!k(e,"sendStickers"),canSendGifs:n||!k(e,"sendGifs"),canAttachEmbedLinks:n||!k(e,"embedLinks")}}function L(e,t,n){if(null!=t&&t.sendMessages){const{untilDate:n}=t;return n&&n2&&void 0!==arguments[2]?arguments[2]:{};return n[e.id]&&void 0!==n[e.id].isMuted?n[e.id].isMuted:e.isMuted||f(e.id)&&!t.hasPrivateChatsNotifications||g(e)&&!t.hasBroadcastNotifications||h(e)&&!t.hasGroupNotifications}function F(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{hasPrivateChatsMessagePreview:r=!0,hasBroadcastMessagePreview:o=!0,hasGroupMessagePreview:d=!0}=t;return n[e.id]&&void 0!==n[e.id].shouldShowPreviews?n[e.id].shouldShowPreviews:f(e.id)&&r||g(e)&&o||h(e)&&d}function O(e){return m(e)||(p(e)||g(e))&&e.isCreator}function D(e,t,n){const{id:r,title:o,emoticon:d,description:a,pinnedChatIds:u,excludedChatIds:i,includedChatIds:s,excludeArchived:c,excludeMuted:l,excludeRead:f,...h}=t;return void 0!==n&&(Object.values(h).filter(Boolean).length>1||null!=i&&i.length||null!=s&&s.length)?e("Chats",n):h.bots?e("FilterBots"):h.groups?e("FilterGroups"):h.channels?e("FilterChannels"):h.contacts?e("FilterContacts"):h.nonContacts?e("FilterNonContacts"):void 0}function Z(e,t,n){if(n&&!f(t))return n.isSelf?e("FromYou"):(0,a.Vl)(n)}function _(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3?arguments[3]:void 0;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+=c),r&&r.includes(e)&&(d=Date.now()+l+(r.length-r.indexOf(e))),d}),"desc")}function $(e,t,n,r,o){if(!r)return t;const d=(0,i.W)(r);return t.filter((t=>{const r=n[t];return!!r&&d(w(e,r,void 0,t===o))}))}},5806:(e,t,n)=>{n.d(t,{lN:()=>F,JE:()=>T,uw:()=>Ce,k6:()=>ue,lb:()=>x,$l:()=>o.$l,kK:()=>r.kK,H5:()=>o.H5,MR:()=>ce,kw:()=>r.kw,cc:()=>o.cc,Qm:()=>o.Qm,RT:()=>o.RT,GM:()=>o.GM,hu:()=>o.hu,N0:()=>pe,Hd:()=>o.Hd,U:()=>o.U,l6:()=>o.l6,T7:()=>v,SB:()=>o.SB,VE:()=>o.VE,XV:()=>we,Sc:()=>be,N5:()=>z,oP:()=>K,qp:()=>j,w6:()=>k,R5:()=>Ie,$D:()=>p,aE:()=>Y,ep:()=>fe,c0:()=>he,d0:()=>c,eO:()=>te,Tp:()=>l,nf:()=>ne,kG:()=>le,Ti:()=>ie,DH:()=>ae,KK:()=>h,O$:()=>W,t9:()=>ee,dT:()=>R,Y5:()=>H,zF:()=>o.zF,q8:()=>o.q8,_O:()=>g,bf:()=>q,Kk:()=>_,Eb:()=>Z,MK:()=>O,UD:()=>m,EU:()=>D,b7:()=>G,kd:()=>J,s1:()=>re,F$:()=>oe,Cg:()=>de,bV:()=>ge,HV:()=>ve,zX:()=>o.zX,OU:()=>E,RI:()=>P,Ow:()=>Ee,Rs:()=>r.Rs,Vl:()=>r.Vl,Js:()=>r.Js,db:()=>r.db,Tq:()=>r.Tq,jC:()=>ye,BM:()=>me,u8:()=>V,Lo:()=>w,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:()=>I,$R:()=>N,CD:()=>A,rl:()=>Q,hC:()=>X,CI:()=>M,B4:()=>y,ss:()=>b,jM:()=>C,cS:()=>r.cS,YC:()=>o.YC,kM:()=>r.kM,Mg:()=>o.Mg,Ak:()=>f,i4:()=>o.i4,Sm:()=>o.Sm,ih:()=>o.ih,Z0:()=>r.Z0});var r=n(3311),o=n(2825),d=n(6137),a=n(3716),u=n(7361),i=n(4784);const s=new RegExp(a.FM,"i");function c(e){return`message${e.toString().replace(".","-")}`}function l(e){const{chatId:t,id:n}=e;return function(e,t){return`msg${e}-${t}`}(t,n)}function f(e){const t=e.match(/^msg(-?\d+)-(\d+)/);return{chatId:t[1],messageId:Number(t[2])}}function h(e){return e.previousLocalId||e.id}function m(e){const{text:t,sticker:n,photo:r,video:o,audio:d,voice:u,document:i,poll:s,webPage:c,contact:l,invoice:f,location:h}=e.content;return t?t.text:n||r||o||d||u||i||l||s||c||f||h?void 0:a.VC}function p(e){const{text:t,sticker:n,photo:r,video:o,audio:d,voice:a,document:u,poll:s,webPage:c,contact:l}=e.content;return!!(n||null!=o&&o.isRound)||!(!t||r||o||d||a||u||s||c||l)&&((0,i.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 v(e){const{text:t}=e.content;let n;if(null!=t&&t.entities){let e=t.entities.find((e=>e.type===d.Vv.TextUrl));if(e&&(n=e.url.match(s)),!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(s)}}if(!n&&t&&(n=t.text.match(s)),n)return{url:n[0],domain:n[3]}}function y(e){return e.isOutgoing}function b(e){return Boolean(e.replyToMessageId)}function I(e){return Boolean(e.forwardInfo)}function w(e){return Boolean(e.content.action)}function C(e){return e.chatId===a.aw&&Math.round(e.id)!==e.id}function S(e){return Boolean(e.senderId)&&!(0,o.YC)(e.senderId)&&y(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>=a.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.isLottie?"tgs":t.sticker.isVideo?"webm":(0,u.on)()?"webp":"png";return`${t.sticker.id}.${e}`}if(t.audio)return t.audio.fileName;const d=l(e);return r?`${d}.jpg`:t.voice?u.m5?`${d}.ogg`:`${d}.wav`:d}function T(e){return!e.results.some((e=>e.count>0))}function N(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now()/1e3;const{location:n}=e.content;return"geoLive"===(null==n?void 0:n.type)&&t-(e.date||0)>=n.period}var L=n(8035);function R(e){var t,n;return e.isOutgoing?null===(t=e.reactions)||void 0===t||null===(n=t.recentReactions)||void 0===n?void 0:n[0]:void 0}function x(e,t,n){if(!e||!e.recentReactions)return!0;if(!t||!t.recentReactions)return!1;if(t.recentReactions.every((e=>e.userId===n)))return!1;const r=e.results.reduce(((e,t)=>(e[t.reaction]=t.count,e)),{});return t.results.some((e=>!r[e.reaction]||r[e.reaction]2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:F,o=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],d=arguments.length>5&&void 0!==arguments[5]&&arguments[5];const a=!n&&Z(t,o),u=a?`${a} `:"",i=(0,L.Z)(D(t),r),s=_(e,t,i,o,d);return`${u}${s}`}function D(e){const t=m(e);if(!t)return;const{entities:n}=e.content.text||{};return null!=n&&n.length?n.reduce(((e,t)=>{let{type:n,offset:r,length:o}=t;if(n!==d.Vv.Spoiler)return e;const a=function(e){return new Array(e).fill(void 0).map((()=>B[Math.floor(Math.random()*B.length)])).join("")}(o);return`${e.substr(0,r)}${a}${e.substr(r+o,e.length)}`}),t):t}function Z(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const{photo:n,video:r,audio:o,voice:d,document:a,sticker:u,poll:i}=e.content;if(e.groupedId||n)return"🖼";if(r)return"📹";if(u)return u.emoji;if(o)return"🎧";if(d)return"🎤";if(a)return"📎";if(i)return"📊";const s=!t&&R(e);return s?s.reaction:void 0}function _(e,t,n){let r=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],o=arguments.length>4&&void 0!==arguments[4]&&arguments[4];const{text:d,photo:u,video:i,audio:s,voice:c,document:l,sticker:f,contact:h,poll:m,invoice:p,location:g}=t.content;let v;t.groupedId&&(v=n||e("lng_in_dlg_album")),u&&(v=n||e("AttachPhoto")),i&&(v=n||e(i.isGif?"AttachGif":"AttachVideo")),f&&(v=e("AttachSticker").trim()),s&&(v=$(t)||e("AttachMusic")),c&&(v=n||e("AttachAudio")),l&&(v=o?l.fileName:n||l.fileName),h&&(v=e("AttachContact")),m&&(v=m.summary.question),p&&(v=`${e("PaymentInvoice")}: ${p.text}`),d&&(o&&v?v+=`\n${n}`:v=n),"geo"!==(null==g?void 0:g.type)&&"venue"!==(null==g?void 0:g.type)||(v=e("Message.Location")),"geoLive"===(null==g?void 0:g.type)&&(v=e("Message.LiveLocation"));const y=!r&&R(t);return v&&y&&(v=`to your "${v}"`),v||a.VC}function $(e){const{audio:t,text:n}=e.content;return t&&[t.title,t.performer].filter(Boolean).join(" — ")||(null==n?void 0:n.text)}var U=n(5376);function j(e){return e.content}function V(e){return Boolean(W(e)||G(e)||Y(e)||q(e)||function(e){return e.content.contact}(e)||ee(e)||z(e)||K(e)||J(e))}function W(e){return e.content.photo}function G(e){return e.content.video}function H(e){const{video:t}=e.content;return null!=t&&t.isRound?t:void 0}function z(e){return e.content.action}function K(e){return e.content.audio}function J(e){return e.content.voice}function q(e){return e.content.sticker}function Y(e){return e.content.document}function Q(e){const t=Y(e);return t?"photo"===t.mediaType:void 0}function X(e){const t=Y(e);return t?"video"===t.mediaType:void 0}function ee(e){return e.content.poll}function te(e){return e.content.invoice}function ne(e){return e.content.location}function re(e){return e.content.webPage}function oe(e){var t;return null===(t=re(e))||void 0===t?void 0:t.photo}function de(e){var t;return null===(t=re(e))||void 0===t?void 0:t.video}function ae(e){var t;return null===(t=function(e){const t=W(e)||G(e)||Y(e)||q(e)||oe(e)||de(e);if(t)return t.thumbnail}(e))||void 0===t?void 0:t.dataUri}function ue(e,t,n,r,o){const{long:d,lat:a,accessHash:u,accuracyRadius:i}=e;return`staticMap:${u}?lat=${a}&long=${d}&w=${t}&h=${n}&zoom=${r}&scale=${o}&accuracyRadius=${i}`}function ie(e,t){const{photo:n,video:r,sticker:o,audio:d,voice:a,document:u}=e.content,i=oe(e),s=de(e),c=r||s,f=n||i,h=f||c||o||d||a||u;if(!h)return;const m=h.id,p=`${l(e)}${m?`:${m}`:""}`;if(c)switch(t){case"micro":case"pictogram":case"viewerPreview":return`${p}?size=m`;case"inline":return me(e)?void 0:se(c,p);case"viewerFull":return se(c,p);case"download":return`${p}?download`}if(f)switch(t){case"micro":case"pictogram":return`${p}?size=m`;case"inline":return me(e)?void 0:`${p}?size=x`;case"viewerPreview":return`${p}?size=x`;case"viewerFull":case"download":return`${p}?size=z`}if(u)switch(t){case"micro":case"pictogram":case"inline":case"viewerPreview":if(!(0,U.v6)(u)||me(e))return;return`${p}?size=m`;case"viewerFull":case"download":return p}if(o)switch(t){case"micro":return;case"pictogram":return`${p}?size=m`;case"inline":return p;case"download":return`${p}?download`}if(d)switch(t){case"micro":case"pictogram":return ce(d)?`${p}?size=m`:void 0;case"inline":return se(d,p);case"download":return`${p}?download`}if(a)switch(t){case"micro":case"pictogram":return;case"inline":return p;case"download":return`${p}?download`}}function se(e,t){return u.I_&&u.s$?`${t}?fileSize=${e.size}&mimeType=${e.mimeType}`:t}function ce(e){return e.thumbnailSizes&&e.thumbnailSizes.length>0}function le(e,t){const{sticker:n,video:r,audio:o,voice:a}=e.content,i=r||de(e);return n&&"inline"===t&&n.isLottie?d.IU.Lottie:i&&u.I_&&("viewerFull"===t||"inline"===t)?d.IU.Progressive:o||a?a&&!u.m5?d.IU.BlobUrl:d.IU.Progressive:d.IU.BlobUrl}function fe(e){const{photo:t,video:n,document:r}=e.content,o=oe(e),d=de(e);if(t||o)return`photo${e.date}.jpeg`;const{fileName:a}=n||d||r||{};return a}function he(e){const{video:t,document:n}=e.content,r=de(e),{size:o}=t||r||n||{};return o}function me(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 pe(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return Ie(e,t,n?"media":"inlineMedia")}function ge(e){return e.sizes.find((e=>"z"===e.type))||e.sizes.find((e=>"y"===e.type))||ve(e)}function ve(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 ye(e){if(e.width&&e.height)return e}function be(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const r=M(e),o=r||n,d=Number(t);return{isUploading:r,isTransferring:o,transferProgress:d}}function Ie(e,t,n){let r;switch(n){case"media":r=e=>{const t=G(e);return W(e)||t&&!t.isRound&&!t.isGif};break;case"documents":r=Y;break;case"links":r=e=>re(e)||function(e){const{text:t}=e.content,n=t&&t.text.match(s);if(n)return{url:n[0],domain:n[3]}}(e);break;case"audio":r=K;break;case"voice":r=e=>{const t=G(e);return J(e)||t&&t.isRound};break;case"inlineMedia":r=e=>{const t=G(e);return W(e)||t&&!t.isRound&&!t.isGif||Q(e)||X(e)};break;default:return[]}return t.reduce(((t,n)=>(e[n]&&r(e[n])&&t.push(n),t)),[])}function we(e){const{audio:t,voice:n,video:r}=j(e),o=t||n||r||de(e);if(o)return o.duration}function Ce(e,t){return`${e}_${t}`}const Se={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 Ee(e){const{message:t,code:n,param:r}=e,{field:o,message:d}=r?Se[r]:Se[n];return{field:o,message:d,description:t}}},3311:(e,t,n)=>{n.d(t,{Js:()=>c,NB:()=>h,Rs:()=>b,Tq:()=>l,Vl:()=>s,Z0:()=>g,cS:()=>m,db:()=>y,kK:()=>v,kM:()=>f,kw:()=>p});var r=n(3716),o=n(790),d=n(782),a=n(2267),u=n(5765);const i=[1,8,5,2,7,4,6];function s(e){if(e)switch(e.type){case"userTypeBot":case"userTypeRegular":return e.firstName||e.lastName;case"userTypeDeleted":case"userTypeUnknown":return"Deleted";default:return}}function 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),a=new Date(1e3*t);if(a>=r)return e("LastSeen.JustNow");const u=new Date(r.getTime()-a.getTime());if(u.getTime()/1e3<60)return e("LastSeen.JustNow");if(u.getTime()/1e3<3600)return e("LastSeen.MinutesAgo",Math.floor(u.getTime()/1e3/60));const i=new Date;if(i.setHours(0,0,0,0),a>new Date(i.getTime()+1e3*d))return u.getTime()/1e3<21600?e("LastSeen.HoursAgo",Math.floor(u.getTime()/1e3/60/60)):e("LastSeen.TodayAt",(0,o.mr)(e,a));const s=new Date;return s.setDate(r.getDate()-1),s.setHours(0,0,0,0),a>new Date(s.getTime()+1e3*d)?e("LastSeen.YesterdayAt",(0,o.mr)(e,a)):e("LastSeen.AtDate",(0,o.Tu)(e,a))}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){let o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0;return(0,d.Xo)(e,(e=>{const d=(0,a.b)(o);if(r&&r.includes(e))return d+172800-(r.length-r.indexOf(e));const u=t[e],i=n[e];if(!u||!i)return 0;if("userStatusOnline"===i.type)return i.expires;if("userStatusOffline"===i.type&&i.wasOnline)return i.wasOnline;switch(i.type){case"userStatusRecently":return d-86400;case"userStatusLastWeek":return d-604800;case"userStatusLastMonth":return d-18144e3;default:return 0}}),"desc")}function v(e,t,n,r,o){if(!n)return e;const d=(0,u.W)(n);return e.filter((e=>{const n=t[e];if(!n)return!1;const a=e===r?o:c(n);return a&&d(a)||d(n.username)}))}function y(e){return"number"==typeof e?Math.abs(e):Math.abs(Number(e))}function b(e){const t=e?y(e.id)%7:0;return i[t]}},3555:(e,t,n)=>{n.d(t,{R3:()=>d,Rd:()=>o,Sv:()=>a,c$:()=>i,iw:()=>u});const r=(0,n(5116).gP)(),o=r.getGlobal,d=r.setGlobal,a=r.getActions,u=r.addActionHandler,i=r.withGlobal},3475:(e,t,n)=>{n.d(t,{B1:()=>u,Dd:()=>p,GL:()=>c,Mg:()=>a,Pi:()=>h,SL:()=>i,a4:()=>s,fZ:()=>l,iX:()=>g,vv:()=>m});var r=n(3716),o=n(782),d=n(1192);function a(e,t,n){return{...e,chats:{...e.chats,listIds:{...e.chats.listIds,[t]:n}}}}function u(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:a(e,t,[...r||[],...o])}function i(e,t){return{...e,chats:{...e.chats,byId:t}}}function s(e,t,n,r){const{byId:o}=e.chats,d=f(e,t,n,r);return d?i(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=i(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=i(e,{...n,...o}):e}function f(e,t,n,r){const{byId:d}=e.chats,a=d[t],u=n.isMin&&a&&!a.isMin,i={...a,...u?(0,o.CE)(n,["isMin","accessHash"]):n,...r&&{photos:[r,...a.photos||[]]}};if(i.id&&i.type)return i}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]}})),s(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=a(e,n,r.filter((e=>e!==t)))),s(e,t,{isNotJoined:!0})}function g(e,t,n){var r;const d=null===(r=t.fullInfo)||void 0===r?void 0:r.members,a=new Set(n.map((e=>e.userId))),u=[...(null==d?void 0:d.filter((e=>!a.has(e.userId))))||[],...n],i=(null==d?void 0:d.map((e=>{let{userId:t}=e;return t})))||[],c=u.map((e=>{let{userId:t}=e;return t}));return(0,o.et)(i,c)?e:s(e,t.id,{fullInfo:{...t.fullInfo,members:u}})}},5406:(e,t,n)=>{n.d(t,{O4:()=>K,iX:()=>r.iX,c_:()=>o.c_,fZ:()=>r.fZ,m6:()=>o.m6,aK:()=>H,aJ:()=>G,zn:()=>P,Sh:()=>y,$S:()=>o.$S,bp:()=>ae,WY:()=>ue,ft:()=>M,K4:()=>o.K4,bV:()=>o.bV,GK:()=>I,M6:()=>o.M6,i9:()=>o.i9,Dd:()=>r.Dd,vy:()=>f,rB:()=>J,g_:()=>c,Mg:()=>r.Mg,SL:()=>r.SL,Pb:()=>F,w3:()=>o.w3,BI:()=>V,lr:()=>W,pf:()=>o.pf,ps:()=>E,s5:()=>m,y9:()=>o.y9,fS:()=>oe,nA:()=>ee,_7:()=>re,Q$:()=>X,Dq:()=>de,vT:()=>Q,QD:()=>ne,QH:()=>te,Ob:()=>o.Ob,a4:()=>r.a4,B1:()=>r.B1,vv:()=>r.vv,Pi:()=>r.Pi,cY:()=>o.cY,GL:()=>r.GL,Wy:()=>o.Wy,wV:()=>o.wV,cq:()=>o.cq,rq:()=>s,No:()=>k,Og:()=>T,xv:()=>L,px:()=>N,xj:()=>o.xj,c1:()=>_,z5:()=>Z,qr:()=>B,dx:()=>O,fw:()=>j,H9:()=>U,HN:()=>z,ff:()=>o.ff,P4:()=>o.P4,TM:()=>Y,Fn:()=>o.Fn,ze:()=>ie,yC:()=>se,Rg:()=>i,z3:()=>u,IM:()=>l,sN:()=>o.sN,Xg:()=>o.Xg,j6:()=>o.j6,lG:()=>o.lG,IE:()=>q,Nq:()=>g,Lm:()=>w,Q3:()=>C,eD:()=>v});var r=n(3475),o=n(4907),d=n(782),a=n(1192);function u(e,t,n,r,o){const a=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,d.ee)(a,"id")},[t]:{...e.stickers[t],hash:n,..."search"===t?{resultIds:o}:{setIds:r.map((e=>{let{id:t}=e;return t}))}}}}}function i(e,t,n){const r=e.stickers.setsById[t]||{},o=e.stickers.added.setIds||[];let d=o;return n.installedDate&&o&&!o.includes(t)&&(d=[t,...d]),!n.installedDate&&null!=o&&o.includes(t)&&(d=d.filter((e=>e!==t))),{...e,stickers:{...e.stickers,added:{...e.stickers.added,setIds:d},setsById:{...e.stickers.setsById,[t]:{...r,...n}}}}}function s(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 c(e,t){return{...e,animatedEmojis:t}}function l(e,t,n,r){const o=[...(0,a.Pk)(e,t),...n||[]],u=(0,d.Tw)(o.map((e=>{let{id:t}=e;return t}))),i=(0,d.ee)(o,"id"),s=u.map((e=>i[e]));return{...e,stickers:{...e.stickers,forEmoji:{emoji:t,stickers:s,hash:r}}}}function f(e){const{emoji:t,stickers:n,hash:r}=e.stickers.forEmoji||{};return t?l(e,t,n,r):e}var h=n(735);function m(e,t){return{...e,users:{...e.users,byId:t}}}function p(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 g(e,t,n){const{byId:r}=e.users,o=b(e,t,n);return o?m(e=p(e,[o]),{...r,[t]:o}):e}function v(e,t){const n=Object.keys(t).reduce(((n,r)=>{const o=b(e,r,t[r]);return o&&(n[r]=o),n}),{});return e=p(e=m(e,{...e.users.byId,...n}),Object.values(n))}function y(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=b(e,d,t[d]);n&&(o[d]=n,r||(r=!0))}return o}),{});return r?e=p(e=m(e,{...n,...o}),Object.values(o)):e}function b(e,t,n){const{byId:r}=e.users,o=r[t],a=n.isMin&&o&&!o.isMin,u={...o,...a?(0,d.CE)(n,["isMin","accessHash"]):n};if(u.id&&u.type)return u}function I(e,t){const{byId:n}=e.users,{userIds:o}=e.contactList||{};return e=m(e={...e,contactList:{userIds:o?o.filter((e=>e!==t)):h.D}},{...n,[t]:{...n[t],isContact:void 0}}),(0,r.a4)(e,t,{settings:void 0})}function w(e,t){return{...e,userSearch:{...e.userSearch,...t}}}function C(e,t){return w(e,{fetchingStatus:t})}function S(e,t,n){const{byId:r}=e.users,o=r[t];return o&&o.fullInfo?g(e,t,{...o,fullInfo:{...o.fullInfo,isBlocked:n}}):e}function E(e,t){return{...e,users:{...e.users,statusesById:t}}}function P(e,t){const{statusesById:n}=e.users,r=Object.keys(t).filter((e=>!n[e]));return r.length?e=E(e,{...n,...(0,d.ei)(t,r)}):e}function M(e){return{...e,newContact:void 0}}const A=e=>`${e.chatId}_${e.id}`;function k(e,t){return{...e,globalSearch:{...e.globalSearch,...t}}}function T(e,t){return k(e,{currentContent:t})}function N(e,t,n,r,o){var a;const{resultsByType:u}=e.globalSearch||{},i=t.reduce(((e,t)=>(e[A(t)]=t,e)),{}),s=null==u||null===(a=u[r])||void 0===a?void 0:a.foundIds;if(void 0!==s&&Object.keys(i).every((e=>s.includes(A(i[e])))))return L(e,{messages:!1});const c=s||[],l=t.map((e=>A(e))),f=Array.prototype.concat(c,l),h=(0,d.et)(c,f)?c:f;return k(e=L(e,{messages:!1}),{resultsByType:{...(e.globalSearch||{}).resultsByType,[r]:{totalCount:n,nextOffsetId:o,foundIds:h}}})}function L(e,t){return k(e,{fetchingStatus:{...e.globalSearch.fetchingStatus,...t}})}var R=n(5806);function x(e,t,n){return{...e,localTextSearch:{byChatThreadKey:{...e.localTextSearch.byChatThreadKey,[t]:n}}}}function B(e,t,n,r,o){const d=(0,R.uw)(t,n);return x(e,d,{...e.localTextSearch.byChatThreadKey[d],isActive:r,query:o})}function F(e,t,n,r,o,d){const a=(0,R.uw)(t,n);return x(e,a,{...e.localTextSearch.byChatThreadKey[a],results:{foundIds:r,totalCount:o,nextOffsetId:d}})}function O(e,t,n,r,o,a){const u=(0,R.uw)(t,n),{results:i}=e.localTextSearch.byChatThreadKey[u]||{},s=(null==i?void 0:i.foundIds)||[],c=$((0,d.Tw)(Array.prototype.concat(s,r)));return F(e,t,n,(0,d.et)(s,c)?s:c,o,a)}function D(e,t,n){return{...e,localMediaSearch:{byChatId:{...e.localMediaSearch.byChatId,[t]:n}}}}function Z(e,t,n){return D(e,t,{...e.localMediaSearch.byChatId[t],currentType:n})}function _(e,t,n,r,o,a){const{resultsByType:u}=e.localMediaSearch.byChatId[t]||{},i=null!=u&&u[n]?u[n].foundIds:[],s=$((0,d.Tw)(Array.prototype.concat(i,r)));return function(e,t,n,r,o,d){return D(e,t,{...e.localMediaSearch.byChatId[t],resultsByType:{...(e.localMediaSearch.byChatId[t]||{}).resultsByType,[n]:{foundIds:r,totalCount:o,nextOffsetId:d}}})}(e,t,n,(0,d.et)(i,s)?i:s,o,a)}function $(e){return e.sort(((e,t)=>t-e))}function U(e,t){return{...e,management:{...e.management,progress:t}}}function j(e,t,n){return{...e,management:{...e.management,byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t]||{},...n}}}}}function V(e,t){return{...e,settings:{...e.settings,byKey:{...e.settings.byKey,...t}}}}function W(e,t,n){return{...e,settings:{...e.settings,themes:{...e.settings.themes,[t]:{...e.settings.themes[t]||{},...n}}}}}function G(e,t){return t.forEach((t=>{const{chatId:n,...r}=t;e=H(e,n,r)})),e}function H(e,t,n){return{...e,settings:{...e.settings,notifyExceptions:{...e.settings.notifyExceptions,[t]:n}}}}function z(e,t,n,r){switch(t){case"contact":return V(e,{...void 0!==n&&{hasPrivateChatsNotifications:!n},...void 0!==r&&{hasPrivateChatsMessagePreview:r}});case"group":return V(e,{...void 0!==n&&{hasGroupNotifications:!n},...void 0!==r&&{hasGroupMessagePreview:r}});case"broadcast":return V(e,{...void 0!==n&&{hasBroadcastNotifications:!n},...void 0!==r&&{hasBroadcastMessagePreview:r}})}}function K(e,t){return e=S(e,t,!0),{...e,blocked:{...e.blocked,ids:[t,...e.blocked.ids],totalCount:e.blocked.totalCount+1}}}function J(e,t){return e=S(e,t,!1),{...e,blocked:{...e.blocked,ids:e.blocked.ids.filter((e=>e!==t)),totalCount:e.blocked.totalCount-1}}}function q(e,t){return{...e,twoFaSettings:{...e.twoFaSettings,...t}}}function Y(e,t){return{...e,payment:{...e.payment,shippingOptions:t}}}function Q(e,t){return{...e,payment:{...e.payment,requestId:t}}}function X(e,t){return{...e,payment:{...e.payment,step:t}}}function ee(e,t){if(!t.content||!t.content.invoice)return e;const{title:n,text:r,amount:o,currency:d,isTest:a,photoUrl:u}=t.content.invoice;return{...e,payment:{...e.payment,invoiceContent:{title:n,text:r,photoUrl:u,amount:o,currency:d,isTest:a}}}}function te(e,t){return{...e,payment:{...e.payment,stripeCredentials:{...t}}}}function ne(e,t){return{...e,payment:{...e.payment,smartGlocalCredentials:{...t}}}}function re(e,t){return{...e,payment:{...e.payment,...t}}}function oe(e,t){return{...e,payment:{...e.payment,confirmPaymentUrl:t}}}function de(e,t,n){if(!t||!n)return{...e,payment:{...e.payment,receipt:void 0}};const{invoice:r}=n.content,{photoUrl:o,text:d,title:a}=r||{};return{...e,payment:{...e.payment,receipt:{...t,photoUrl:o,text:d,title:a}}}}function ae(e){return{...e,payment:{}}}function ue(e){return{...e,payment:{...e.payment,isPaymentModalOpen:!1}}}function ie(e,t,n){return{...e,statistics:{byChatId:{...e.statistics.byChatId,[t]:n}}}}function se(e,t,n,r){return{...e,statistics:{byChatId:{...e.statistics.byChatId,[t]:{...e.statistics.byChatId[t]||{},[n]:r}}}}}},4907:(e,t,n)=>{n.d(t,{$S:()=>w,Fn:()=>A,K4:()=>g,M6:()=>T,Ob:()=>N,P4:()=>p,Wy:()=>u,Xg:()=>S,bV:()=>v,cY:()=>m,c_:()=>h,cq:()=>M,ff:()=>b,i9:()=>L,j6:()=>E,lG:()=>R,m6:()=>f,pf:()=>l,sN:()=>s,w3:()=>P,wV:()=>k,xj:()=>y,y9:()=>C});var r=n(6137),o=n(3716),d=n(1192),a=n(782);function u(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:r._f,d=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"thread",a=arguments.length>4?arguments[4]:void 0;const{messageLists:u}=e.messages;let i=u;if(a||o.Cg)i=t?[{chatId:t,threadId:n,type:d}]:[];else if(t){const e=u[u.length-1];e&&e.chatId===t&&e.threadId===n&&e.type===d||(i=e&&e.chatId===o.AJ?[...u.slice(0,-1),{chatId:t,threadId:n,type:d}]:[...u,{chatId:t,threadId:n,type:d}])}else i=u.slice(0,-1);return{...e,messages:{...e.messages,messageLists:i}}}function i(e,t,n){return c(e,t,{byId:n})}function s(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}}})}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 s(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,d.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,d.Zw)(e,t)||{},a={...o[n],...r};return a.id?i(e,t,{...o,[n]:a}):e}function p(e,t,n,r){const o=(0,d.Fn)(e,t)||{},a={...o[n],...r};return a.id?P(e,t,{...o,[n]:a}):e}function g(e,t,n){const r=(0,d.Zw)(e,t);if(!r)return e;const o=(0,a.CE)(r,n),s=Object.values((0,a.q0)(r,n)).filter((e=>{let{forwardInfo:t}=e;return null==t?void 0:t.isLinkedChannelPost}));if(Object.keys(e.messages.byChatId[t].threadsById).map(Number).forEach((r=>{const o=(0,d.tZ)(e,t,r);let a=(0,d.gb)(e,t,r),u=(0,d.qC)(e,t,r),i=(0,d.Cb)(e,t,r),s=(0,d.KB)(e,t),c=null==o?void 0:o.messagesCount;n.forEach((e=>{a&&a.includes(e)&&(a=a.filter((t=>t!==e)),void 0!==c&&(c-=1)),u&&u.includes(e)&&(u=u.filter((t=>t!==e))),i&&i.includes(e)&&(i=i.filter((t=>t!==e))),s&&s.includes(e)&&(s=s.filter((t=>t!==e)))})),e=l(e,t,r,"listedIds",a),e=l(e,t,r,"outlyingIds",u),e=l(e,t,r,"viewportIds",i),e=l(e,t,r,"pinnedIds",s),o&&void 0!==c&&(e=l(e,t,r,"threadInfo",{...o,messagesCount:c}))})),s.length){const n=(0,d.Bt)(e),r=n&&n.chatId===t&&"thread"===n.type,o=null==n?void 0:n.threadId;s.forEach((n=>{const{fromChatId:a,fromMessageId:i}=n.forwardInfo,s=(0,d.hj)(e,a,i);r&&o===i&&(e=u(e,t)),s&&(e=m(e,a,i,{threadInfo:void 0}))}))}return e=i(e,t,o)}function v(e,t,n){const o=(0,d.Fn)(e,t);if(!o)return e;const u=(0,a.CE)(o,n);let i=(0,d.qy)(e,t);return i&&(n.forEach((e=>{i.includes(e)&&(i=i.filter((t=>t!==e)))})),e=l(e,t,r._f,"scheduledIds",i)),P(e,t,u)}function y(e,t,n,r){const o=(0,d.gb)(e,t,n),a=null!=o&&o.length?r.filter((e=>!o.includes(e))):r;return o&&!a.length?e:l(e,t,n,"listedIds",I([...o||[],...a]))}function b(e,t,n,r){const o=(0,d.qC)(e,t,n),a=null!=o&&o.length?r.filter((e=>!o.includes(e))):r;return o&&!a.length?e:l(e,t,n,"outlyingIds",I([...o||[],...a]))}function I(e){return e.sort(((e,t)=>e-t))}function w(e,t,n,r){const a=(0,d.Cb)(e,t,n)||[];return a.includes(r)?e:l(e,t,n,"viewportIds",I([...a.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){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],o=arguments.length>4&&void 0!==arguments[4]&&arguments[4];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,u,i){let s=arguments.length>7&&void 0!==arguments[7]&&arguments[7];const{selectedMessages:c}=e;u&&(i=(0,d.xH)(e,t,u));const l=i||[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(s&&f.length){const u=(0,d.$W)(e,t,n,r),i=u.indexOf(f[f.length-1]),s=u.indexOf(o),c=Math.min(i,s),l=Math.max(i,s),m=u.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:a,fromChatId:u}=t.forwardInfo||{};if(a&&u){const t=(0,d.tZ)(e,n,a);t&&(e=l(e,n,a,"threadInfo",{...t,lastMessageId:r,messagesCount:t.messagesCount+(o?-1:1)}))}return e}},4342:(e,t,n)=>{n.d(t,{DI:()=>b,Ek:()=>g,FM:()=>i,IK:()=>f,Mw:()=>v,N:()=>p,P_:()=>c,UW:()=>I,YK:()=>l,Z1:()=>u,_5:()=>w,ep:()=>y,g4:()=>m,pk:()=>h,xo:()=>s});var r=n(6137),o=n(5806),d=n(6087),a=n(3716);function u(e,t){return e.chats.byId[t]}function i(e,t){return t===e.currentUserId}function s(e,t){const n=function(e,t){const n=(0,o.zX)(t);return!!n&&(0,d.dy)(e,n)}(e,t);return n&&(0,o.cS)(n)}function c(e){return Object.values(e.chats.byId).find((e=>{let{isSupport:t}=e;return t}))}function l(e,t){if(!(0,o.YC)(t.id)&&!(0,o.eA)(t)&&t.fullInfo)return t.fullInfo.members&&t.fullInfo.members.length!==a.mo?t.fullInfo.members.reduce(((t,n)=>{let{userId:r}=n;return r!==e.currentUserId&&e.users.byId[r]&&(0,o.kM)(e.users.byId[r],e.users.statusesById[r])?t+1:t}),0):t.fullInfo.onlineCount}function f(e,t){const n=u(e,t),r=n&&(0,o.zX)(n),a=r&&(0,d.dy)(e,r);if(a&&(0,o.cS)(a))return a}function h(e,t){const n=u(e,t),d=f(e,t);if(!n||!d)return!1;if(n.lastMessage&&(0,o.CD)(n.lastMessage))return!0;const a=e.messages.byChatId[t];if(!a)return!1;const{listedIds:i}=a.threadsById[r._f]||{};return i&&!i.length}function m(e){return Boolean(e.chats.listIds.active)}function p(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 g(e,t){const n=u(e,t);if(n&&p(e,t))return n.folderId===a.WS?"archived":"active"}function v(e,t){return e.chatFolders.byId[t]}function y(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:a.Nf;const{active:r,archived:o}=e.chats.orderedPinnedIds;if(n===a.Nf)return Boolean(null==r?void 0:r.includes(t));if(n===a.WS)return Boolean(null==o?void 0:o.includes(t));const{byId:d}=e.chatFolders,{pinnedChatIds:u}=d[n]||{};return Boolean(null==u?void 0:u.includes(t))}function b(e,t){const n=t.toLowerCase();return Object.values(e.chats.byId).find((e=>e.username&&e.username.toLowerCase()===n))}function I(e){return Boolean(u(e,a.aw))}function w(e,t){var n;const r=u(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)||u(e,o):void 0}},1192:(e,t,n)=>{n.d(t,{xs:()=>he,_k:()=>ie,zB:()=>v,tH:()=>y,Oh:()=>b,g4:()=>u.g4,bH:()=>Me,__:()=>ke,xl:()=>se,Nu:()=>le,nB:()=>ce,Eh:()=>De,Z1:()=>u.Z1,IK:()=>u.IK,DI:()=>u.DI,Mw:()=>u.Mw,Ek:()=>u.Ek,hj:()=>Q,ZB:()=>te,Zw:()=>A,YK:()=>u.YK,X5:()=>ye,jr:()=>M,yN:()=>f,JX:()=>ze,pP:()=>je,we:()=>_e,$W:()=>R,Bt:()=>P,y5:()=>l,n5:()=>Ze,q6:()=>Be,Ms:()=>j,s:()=>_,_$:()=>Z,kK:()=>ee,hI:()=>U,wU:()=>$,yZ:()=>G,It:()=>ge,G$:()=>ne,y8:()=>we,cv:()=>ue,ku:()=>Re,pk:()=>u.pk,N:()=>u.N,ep:()=>u.ep,xo:()=>u.xo,FM:()=>u.FM,a6:()=>Se,te:()=>fe,Ev:()=>ve,CA:()=>be,zQ:()=>Ve,_X:()=>re,KA:()=>q,EV:()=>Le,vk:()=>Ie,Jf:()=>Ge,UW:()=>u.UW,s4:()=>i.s4,b9:()=>Y,VF:()=>Ne,gb:()=>N,CP:()=>I,cu:()=>w,ji:()=>C,aW:()=>Ue,xH:()=>Ce,FT:()=>Pe,tV:()=>V,NJ:()=>rt,dZ:()=>nt,dT:()=>de,qC:()=>L,gx:()=>Ke,eh:()=>qe,Mz:()=>Je,sp:()=>Ye,KB:()=>B,EB:()=>Xe,$$:()=>Qe,rd:()=>pe,p9:()=>H,Yy:()=>D,Wq:()=>We,qy:()=>F,Tm:()=>X,Fn:()=>k,Vt:()=>O,D7:()=>Ee,_5:()=>u._5,Ur:()=>ae,yB:()=>Te,Aq:()=>Oe,Jg:()=>tt,fS:()=>xe,aT:()=>$e,Ny:()=>h,E_:()=>m,Pk:()=>p,i3:()=>et,P_:()=>u.P_,Pu:()=>He,Db:()=>J,tZ:()=>W,Cm:()=>z,qS:()=>K,uZ:()=>me,dy:()=>i.dy,Bk:()=>i.Bk,ss:()=>i.ss,Cb:()=>x,P2:()=>Fe});var r=n(1713),o=n(7361),d=n(6137),a=n(3716),u=n(4342),i=n(6087),s=n(5806),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((e=>{let{packs:n}=e;n&&(r=r.concat(n[t]||[],n[g(t)]||[]))})),r}function g(e){return e.replace("️","")}function v(e,t){const{animatedEmojis:n}=e;if(!n||!n.stickers)return;const r=g(t);return n.stickers.find((e=>e.emoji===t||e.emoji===r))}function y(e,t){const{animatedEmojiEffects:n}=e;if(!n||!n.stickers)return;const r=g(t);return n.stickers.find((e=>e.emoji===t||e.emoji===r))}function b(e,t){var n;return null==e||null===(n=e.appConfig)||void 0===n?void 0:n.emojiSounds[g(t)]}function I(e,t){const n=g(t);return"🍑"===n?"Peach":"🍆"===n?"Eggplant":void 0}function w(e){return"Eggplant"===e?"Cumshot":void 0}function C(e){return"Cumshot"===e?"🍆":void 0}var S=n(2267),E=n(735);function P(e){const{messageLists:t}=e.messages;if(t.length)return t[t.length-1]}function M(e){const{chatId:t}=P(e)||{};return t?(0,u.Z1)(e,t):void 0}function A(e,t){var n;return null===(n=e.messages.byChatId[t])||void 0===n?void 0:n.byId}function k(e,t){var n;return null===(n=e.scheduledMessages.byChatId[t])||void 0===n?void 0:n.byId}function T(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 N(e,t,n){return T(e,t,n,"listedIds")}function L(e,t,n){return T(e,t,n,"outlyingIds")}function R(e,t,n,r){switch(r){case"thread":return x(e,t,n);case"pinned":return B(e,t);case"scheduled":return F(e,t)}}function x(e,t,n){return T(e,t,n,"viewportIds")}function B(e,t){return T(e,t,d._f,"pinnedIds")}function F(e,t){return T(e,t,d._f,"scheduledIds")}function O(e,t,n){return T(e,t,n,"scrollOffset")}function D(e,t,n){return T(e,t,n,"replyingToId")}function Z(e,t,n){return T(e,t,n,"editingId")}function _(e,t,n){return T(e,t,n,"editingDraft")}function $(e,t){return T(e,t,d._f,"editingScheduledId")}function U(e,t){return T(e,t,d._f,"editingScheduledDraft")}function j(e,t,n){return T(e,t,n,"draft")}function V(e,t,n){return T(e,t,n,"noWebPage")}function W(e,t,n){return T(e,t,n,"threadInfo")}function G(e,t,n){return T(e,t,n,"firstMessageId")}function H(e,t,n){return T(e,t,n,"replyStack")}function z(e,t,n){if(n===d._f)return(0,u.Z1)(e,t);const r=W(e,t,n);return r?(0,u.Z1)(e,r.originChannelId||t):void 0}function K(e,t,n){if(n===d._f)return;const r=W(e,t,n);return r?r.topMessageId:void 0}function J(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 q(e,t,n){const r=P(e);if(!r)return!1;const{threadInfo:o}=J(e,t,n)||{};return t===r.chatId&&(r.threadId===d._f||o&&r.threadId===o.threadId)}function Y(e,t,n){const r=x(e,t,n);if(!r||!r.length)return!0;let o;if(n===d._f){const n=(0,u.Z1)(e,t);if(!n||!n.lastMessage)return!0;o=n.lastMessage.id}else{const r=W(e,t,n);if(!r||!r.lastMessageId)return;o=r.lastMessageId}return o>=a.AE&&!Q(e,t,o)||r[r.length-1]>=o}function Q(e,t,n){const r=A(e,t);return r?r[n]:void 0}function X(e,t,n){const r=k(e,t);return r?r[n]:void 0}function ee(e,t,n,r){if("scheduled"===r){const n=$(e,t);return n?X(e,t,n):void 0}{const r=Z(e,t,n);return r?Q(e,t,r):void 0}}function te(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 ne(e,t){const{chatId:n,messageId:r}=e.focusedMessage||{};return n===t?r:void 0}function re(e,t){const n=ne(e,t.chatId);return!!n&&(n===t.id||n===t.previousLocalId)}function oe(e,t){const{lastReadOutboxMessageId:n}=(0,u.Z1)(e,t.chatId)||{};return(0,s.CI)(t)||!n||n2&&void 0!==arguments[2]&&arguments[2];return oe(e,t)||n?(0,s.RI)(t):"read"}function ae(e,t){const{senderId:n}=t;if(n)return(0,s.YC)(n)?(0,i.dy)(e,n):(0,u.Z1)(e,n)}function ue(e,t){const{forwardInfo:n}=t;if(n)return n.isChannelPost&&n.fromChatId?(0,u.Z1)(e,n.fromChatId):n.senderUserId?(0,i.dy)(e,n.senderUserId)||(0,u.Z1)(e,n.senderUserId):void 0}function ie(e,t,n){var r,o,d,a,i;const c=(0,u.Z1)(e,t.chatId);if(!c||c.isRestricted)return{};const l=(0,s.YC)(c.id),f=(0,u.FM)(e,t.chatId),h=(0,s.G9)(c),m=(0,s.ZV)(c),p=(0,s.eA)(c),g=(0,s.CI)(t),v=(0,s.jM)(t),y=(0,s.B4)(t),b=(0,s.Lo)(t),{content:I}=t,w=(f||m&&(0,s.VE)(c,"pinMessages")||p&&(0,s.VE)(c,"editMessages")||(0,S.b)(e.serverTimeOffset)-t.date<172800)&&!(I.sticker||I.contact||I.poll||I.action||I.audio||null!==(r=I.video)&&void 0!==r&&r.isRound||I.location)&&!(0,s.MF)(t)&&!t.viaBotId,C=!g&&!v&&(0,s.Qm)(c,n),E=l||c.isCreator||!p&&!(0,s.Mg)(c,"pinMessages")||(0,s.VE)(c,"pinMessages");let P=!g&&!v&&!b&&E,M=!1;const A=B(e,c.id);P&&(M=Boolean(A&&A.includes(t.id)),P=!M);const k=!g&&!v&&(l||y||h||c.isCreator||(0,s.VE)(c,"deleteMessages")),T=!l&&!y,N=k&&(l&&!f||h&&(y||(0,s.VE)(c,"deleteMessages")||c.isCreator)),L=!g&&!b&&w&&(y||p&&(c.isCreator||(0,s.VE)(c,"editMessages"))),R=!g&&!b,x=Boolean(t.content.sticker),F=x&&function(e,t){const{stickers:n}=e.stickers.favorite;return n&&n.some((e=>{let{id:n}=e;return n===t.id}))}(e,t.content.sticker),O=!b&&x&&!F,D=!b&&F,Z=!b,_=!b&&(p||m),$=!b,U=Boolean((null===(o=I.webPage)||void 0===o?void 0:o.document)||(null===(d=I.webPage)||void 0===d?void 0:d.video)||(null===(a=I.webPage)||void 0===a?void 0:a.photo)||I.audio||I.voice||I.photo||I.video||I.document||I.sticker),j=null===(i=t.content.video)||void 0===i?void 0:i.isGif;return{noOptions:[C,L,P,M,T,k,N,R,O,D,Z,_,$,U,j].every((e=>!e)),canReply:C,canEdit:L,canPin:P,canUnpin:M,canReport:T,canDelete:k,canDeleteForAll:N,canForward:R,canFaveSticker:O,canUnfaveSticker:D,canCopy:Z,canCopyLink:_,canSelect:$,canDownload:U,canSaveGif:j}}function se(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=P(e)||{},o=n&&A(e,n);if(!o||!t||!r)return{};const d=t.map((t=>o[t]&&ie(e,o[t],r))).filter(Boolean);return{canDelete:d.every((e=>e.canDelete)),canDeleteForAll:d.every((e=>e.canDeleteForAll))}}function ce(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=P(e)||{},o=n&&A(e,n);return!!(o&&t&&r)&&t.map((t=>o[t]&&ie(e,o[t],r))).filter(Boolean).every((e=>e.canReport))}function le(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=P(e)||{},o=n&&A(e,n);return!!(o&&t&&r)&&t.map((t=>o[t]&&ie(e,o[t],r))).filter(Boolean).some((e=>e.canDownload))}function fe(e,t){const n=e.activeDownloads.byChatId[t.chatId];return!!n&&n.includes(t.id)}function he(e,t){return e.activeDownloads.byChatId[t]||E.D}function me(e,t){var n;return null===(n=e.fileUploads.byMessageLocalId[t.previousLocalId||t.id])||void 0===n?void 0:n.progress}function pe(e,t,n){if(n===d._f){const n=(0,u.Z1)(e,t);if(!n)return;if(!n.lastReadInboxMessageId)return;return n.lastMessage?(0,s.CI)(n.lastMessage)?n.lastMessage.id:Math.min(n.lastMessage.id,n.lastReadInboxMessageId):n.lastReadInboxMessageId}{const r=W(e,t,n);if(!r)return;return r.lastReadInboxMessageId?Math.min(r.lastReadInboxMessageId,r.lastMessageId||1/0):r.topMessageId}}function ge(e,t,n){const r=(0,u.Z1)(e,t);if(n===d._f){if(!r)return}else{const r=W(e,t,n);if(!r||void 0!==r.lastMessageId&&r.lastMessageId===r.lastReadInboxMessageId)return}const o=L(e,t,n),i=N(e,t,n),s=A(e,t);if(!s||!o&&!i)return;const c=pe(e,t,n);if(!c&&r&&r.isNotJoined)return;const l=t===a.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)&&s[e]&&(!s[e].isOutgoing||s[e].isFromScheduled)&&e>l))}if(o){const e=f(o);if(e)return e}if(i){const e=f(i);if(e)return e}}function ve(e){const{forwardMessages:t}=e;return Boolean(t.isModalShown)}function ye(e,t){const n=Object.values(e.chats.byId).find((e=>(0,s.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,u.Z1)(e,n);return o&&(0,s.Ru)(o)&&r[o.id].byId[t]}))}function be(e){const{selectedMessages:t}=e;return Boolean(t)}function Ie(e,t){const{messageIds:n}=e.selectedMessages||{};return!!n&&n.includes(t)}function we(e,t,n){const r=A(e,t);if(r)return Object.values(r).filter((e=>e.groupedId===n&&e.forwardInfo)).map((e=>{let{forwardInfo:t}=e;return t.fromMessageId}))}function Ce(e,t,n){const r=A(e,t);if(r)return Object.keys(r).map(Number).filter((e=>r[e].groupedId===n))}function Se(e,t,n){const{messageIds:r}=e.selectedMessages||{};if(!r)return!1;const o=Ce(e,t,n);return o&&o.every((e=>r.includes(e)))}function Ee(e){const{messageIds:t}=e.selectedMessages||{};return t?t.length:0}function Pe(e,t){const n=(0,u.Z1)(e,t);if(!n)return;if(!(0,u.xo)(e,n))return;const r=A(e,t),o=x(e,t,d._f);if(!r||!o)return;const a=(0,c.dF)(o,(e=>!r[e].isOutgoing&&Boolean(r[e].keyboardButtons))),i=(0,c.dF)(o,(e=>Boolean(r[e].shouldHideKeyboardButtons)));return a&&i&&i>a?void 0:a?r[a]:void 0}function Me(e,t){const n=(0,u.Z1)(e,t.chatId);if(!n)return;const r=ae(e,t),o=Boolean((0,s.O$)(t)||(0,s.F$)(t)),d=Boolean((0,s.b7)(t)||(0,s.Cg)(t)),a=Boolean((0,s.oP)(t)||(0,s.kd)(t)||(0,s.aE)(t)),{canAutoLoadPhotoFromContacts:i,canAutoLoadPhotoInPrivateChats:c,canAutoLoadPhotoInGroups:l,canAutoLoadPhotoInChannels:f,canAutoLoadVideoFromContacts:h,canAutoLoadVideoInPrivateChats:m,canAutoLoadVideoInGroups:p,canAutoLoadVideoInChannels:g,canAutoLoadFileFromContacts:v,canAutoLoadFileInPrivateChats:y,canAutoLoadFileInGroups:b,canAutoLoadFileInChannels:I}=e.settings.byKey;return o?Ae({global:e,chat:n,sender:r,canAutoLoadMediaFromContacts:i,canAutoLoadMediaInPrivateChats:c,canAutoLoadMediaInGroups:l,canAutoLoadMediaInChannels:f}):d?Ae({global:e,chat:n,sender:r,canAutoLoadMediaFromContacts:h,canAutoLoadMediaInPrivateChats:m,canAutoLoadMediaInGroups:p,canAutoLoadMediaInChannels:g}):!a||Ae({global:e,chat:n,sender:r,canAutoLoadMediaFromContacts:v,canAutoLoadMediaInPrivateChats:y,canAutoLoadMediaInGroups:b,canAutoLoadMediaInChannels:I})}function Ae(e){let{global:t,chat:n,sender:r,canAutoLoadMediaFromContacts:o,canAutoLoadMediaInPrivateChats:d,canAutoLoadMediaInGroups:a,canAutoLoadMediaInChannels:u}=e;const c=Boolean(r&&(r.id===t.currentUserId||(0,i.nM)(t,r)));return Boolean(c&&o||!c&&d&&(0,s.YC)(n.id)||a&&(0,s.Bf)(n)||u&&(0,s.eA)(n))}function ke(e,t){const n=(0,s.b7)(t)||(0,s.Cg)(t);if(!n)return;const{canAutoPlayVideos:r,canAutoPlayGifs:o}=e.settings.byKey,d=n.isGif||n.isRound;return r&&!d||o&&d}function Te(e){return e.settings.byKey.shouldLoopStickers}function Ne(e){const{serviceNotifications:t}=e,n=Math.max(...t.map((e=>{let{id:t}=e;return t})));return t.find((e=>{let{id:t}=e;return t===n}))}function Le(e,t){var n;return!!t&&(t.isProtected||(null===(n=(0,u.Z1)(e,t.chatId))||void 0===n?void 0:n.isProtected))}function Re(e,t,n){var r;if(null!==(r=(0,u.Z1)(e,t))&&void 0!==r&&r.isProtected)return!0;if(!n)return!1;const o=A(e,t);return n.some((e=>{var t;return null===(t=o[e])||void 0===t?void 0:t.isProtected}))}function xe(e,t){const n=(0,u.Z1)(e,t),r=n&&(0,s.eA)(n)?e.messages.sponsoredByChatId[t]:void 0;return r&&r.expiresAt>=Math.round(Date.now()/1e3)?r:void 0}function Be(e,t){var n,r,o;if(t===a.aw)return;const d=(0,s.YC)(t),i=null===(n=e.appConfig)||void 0===n?void 0:n.defaultReaction,{availableReactions:c}=e;if(!i||null==c||!c.some((e=>e.reaction===i&&!e.isInactive)))return;if(d)return i;const l=null===(r=(0,u.Z1)(e,t))||void 0===r||null===(o=r.fullInfo)||void 0===o?void 0:o.enabledReactions;return null!=l&&l.includes(i)?i:void 0}function Fe(e){const{chatId:t,threadId:n}=P(e)||{};if(!t||!n)return;const r=T(e,t,n,"viewportIds");return r?r.map((n=>{const{senderId:r}=Q(e,t,n)||{};return r?(0,i.dy)(e,r):void 0})).filter(Boolean):void 0}function Oe(e){var t;return"scheduled"===(null===(t=P(e))||void 0===t?void 0:t.type)}function De(e,t){var n;const r=(0,u.FM)(e,t),o=t===a.FV&&(0,u.IK)(e,t);return Boolean(!r&&!o&&(0,s.YC)(t)&&(null===(n=(0,i.ss)(e,t))||void 0===n?void 0:n.wasOnline))}function Ze(e){const{chatId:t,threadId:n}=P(e)||{};if(!t||!n)return;const r=(0,s.uw)(t,n),o=e.localTextSearch.byChatThreadKey[r];return o&&o.isActive?o:void 0}function _e(e){const{chatId:t}=P(e)||{};if(t)return e.localMediaSearch.byChatId[t]}function $e(e,t){return e.statistics.byChatId[t]}function Ue(e,t){return e.management.byChatId[t]}function je(e){const{chatId:t,threadId:n}=P(e)||{};if(!t||!n)return;if((0,s.YC)(t))return"user";const r=(0,u.Z1)(e,t);return r?(0,s.Bf)(r)?"group":"channel":void 0}function Ve(e){const{mediaViewer:t}=e;return Boolean(t.messageId||t.avatarOwnerId)}function We(e){return function(e){const{pollResults:t}=e;return Boolean(t.messageId)}(e)?r.qt.PollResults:!o.wB&&Ze(e)?r.qt.Search:function(e){const{chatId:t,threadId:n}=P(e)||{};if(!t||!n)return;const r=e.management.byChatId[t];return r&&r.isActive?r:void 0}(e)?r.qt.Management:function(e){var t;if(!e.isStatisticsShown)return!1;const{chatId:n}=P(e)||{},r=n?(0,u.Z1)(e,n):void 0;return null==r||null===(t=r.fullInfo)||void 0===t?void 0:t.canViewStatistics}(e)?r.qt.Statistics:void 0!==l(e).query?r.qt.StickerSearch:void 0!==f(e).query?r.qt.GifSearch:e.newChatMembersProgress!==r.WB.Closed?r.qt.AddingMembers:e.isChatInfoShown&&P(e)?r.qt.ChatInfo:void 0}function Ge(e){return void 0!==We(e)}function He(e){const{theme:t,shouldUseSystemTheme:n}=e.settings.byKey;return n?(0,o.vn)():t}function ze(e){return e.globalSearch.query}function Ke(e){return e.payment.chatId}function Je(e){return e.payment.messageId}function qe(e){return e.payment.formId}function Ye(e){return e.payment.requestId}function Qe(e){var t;return null===(t=e.payment.nativeParams)||void 0===t?void 0:t.publishableKey}function Xe(e){var t;return null===(t=e.payment.nativeParams)||void 0===t?void 0:t.publicToken}function et(e){return e.payment.stripeCredentials}function tt(e){return e.payment.smartGlocalCredentials}function nt(e){return e.settings.byKey}function rt(e){return e.settings.notifyExceptions}},6087:(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 a(e,t){const n=t.replace(/[^0-9]/g,"");return Object.values(e.users.byId).find((e=>(null==e?void 0:e.phoneNumber)===n))}function u(e,t){return e.contactList&&e.contactList.userIds.includes(t.id)}n.d(t,{Bk:()=>a,dy:()=>r,nM:()=>u,s4:()=>d,ss:()=>o})},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=function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];const[t,n]=(0,r.eJ)(e),o=(0,r.I4)((()=>{n(!0)}),[]),d=(0,r.I4)((()=>{n(!1)}),[]);return[t,o,d]}},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,{YW:()=>s,ZP:()=>c,zG:()=>i});var r=n(4050);const o="tt-event-heavy-animation-start",d="tt-event-heavy-animation-end";let a,u=!1;function i(){return u}function s(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;function t(){a&&(clearTimeout(a),a=void 0),u=!1,document.dispatchEvent(new Event(d))}return u||(u=!0,document.dispatchEvent(new Event(o))),a&&(clearTimeout(a),a=void 0),a=window.setTimeout(t,e),t}const c=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];(0,r.d4)((()=>{if(!n)return u&&e(),document.addEventListener(o,e),document.addEventListener(d,t),()=>{document.removeEventListener(d,t),document.removeEventListener(o,e)}}),[n,t,e])}},6590:(e,t,n)=>{n.d(t,{Oy:()=>i,Wv:()=>l,ZP:()=>h});var r=n(4050),o=n(7361),d=n(7204),a=n(3555),u=n(782);const i=window.location.hash,s=`${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){let i=arguments.length>4&&void 0!==arguments[4]&&arguments[4],l=arguments.length>5?arguments[5]:void 0;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)([]),v=(0,d.Z)(l),y=(0,r.sO)(!1),b=(0,r.I4)((function(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(l){const e=v||[];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(y.current)y.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((e=>{let{index:t}=e;c.currentIndexes.splice(c.currentIndexes.indexOf(t),1)}))}l.length>0&&setTimeout((()=>{const e=++c.currentIndex;c.currentIndexes[c.currentIndexes.length-1]=e,window.history.replaceState({index:e,state:o},"",`${s}#${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&&!i?"replaceState":"pushState"]({index:e,state:o},""),f.current=e,i&&(c.nextStateIndexToReplace=c.currentIndex+1)}),0)),!t&&e||p.current||(f.current!==c.currentIndex&&i||(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,v,i]);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&&(y.current=!0,g.current.pop()),c.currentIndexes.splice(c.currentIndexes.indexOf(r),1),t&&(c.isEdge&&(0,a.Sv)().disableHistoryAnimations(),t(!c.isEdge),p.current=!0)):o===r&&p.current&&n&&!l&&(h.current=!0,c.isEdge&&(0,a.Sv)().disableHistoryAnimations(),n(e.state.state))}catch(e){}},o=l?!v||!(0,u.et)(v,l):m!==e;return!c.isDisabled&&o&&b(),window.addEventListener("popstate",r),()=>window.removeEventListener("popstate",r)}),[o,b,l,e,t,n,v,m,i]),{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},"",s)},2313:(e,t,n)=>{n.d(t,{Z:()=>o});var r=n(4050);const o=(e,t,n,o,d)=>{const[a,u]=(0,r.eJ)(-1);return(0,r.d4)((()=>{u(-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(a);if(38!==t.keyCode&&40!==t.keyCode)return;const d=document.activeElement,i=Array.from(o?r.querySelectorAll(o):r.children);let s=d&&i.indexOf(d)||a;if(38===t.keyCode&&s>0)s--;else if(40===t.keyCode&&s{n.d(t,{Z:()=>a});var r=n(711),o=n(5326),d=n(9290);const a=()=>{const e=(0,o.Z)();return(0,d.Z)((()=>r.ll(e)),[e]),r.i0}},8778:(e,t,n)=>{n.d(t,{Z:()=>a});var r=n(4050),o=n(9203),d=n(5326);const a=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],a=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const u=(0,o.o5)(e,t),i=(0,d.Z)();return(0,r.d4)((()=>{if(a)return(0,o.Qt)(i)}),[a,i]),(0,r.d4)((()=>{n||u||(0,o.$y)(e,t).then(i)}),[e,i,u,t,n]),u}},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=function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],d=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"fast",a=arguments.length>4&&void 0!==arguments[4]&&arguments[4];const[u,i]=(0,r.eJ)(!e),s=(0,r.sO)(),[c,l]=(0,r.eJ)(e&&n);if(e)i(!1),l(!0),s.current&&(window.clearTimeout(s.current),s.current=void 0);else if(l(!1),!u&&!s.current){const e=()=>{i(!0),t&&t(),s.current=void 0};a?e():s.current=window.setTimeout(e,350)}const f=c&&!(a&&!e),h=Boolean(s.current),m=e||h,p=(0,o.Z)(d&&"opacity-transition",d,f&&"open",m&&"shown",h&&"closing");return{shouldRender:m,transitionClassNames:p}}},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:()=>i,lQ:()=>m,xg:()=>s});var r=n(3716);const o=new Set(["scroll","mouseenter","mouseleave"]),d={},a={},u=new Map;function i(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const o=c(t,e);l(o,e,r)?f(o,e,n):e.addEventListener(o,n,r)}function s(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const o=c(t,e);l(o,e,r)?h(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,n){d[e]||(d[e]=0,document.addEventListener(e,p)),function(e){return a[e]||(a[e]=new Map),a[e]}(e).set(t,n),function(e){const t=u.get(e);if(t)return t;const n=new Set;return u.set(e,n),n}(t).add(e),d[e]++}function h(e,t){d[e]--,d[e]||document.removeEventListener(e,p),a[e].delete(t),u.get(t).delete(e)}function m(e){const t=u.get(e);t&&(t.forEach((t=>h(t,e))),u.delete(e))}function p(e){const t=a[e.type];if(t){let n=!1,r=e.target;const o=()=>{n=!0},d=()=>{e.preventDefault()},a=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(a),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(a).length,r=Object.values(a).reduce(((e,t)=>e+t.size),0),o=u.size,i=Array.from(u.values()).reduce(((e,t)=>e+t.size),0);console.warn("DELEGATED EVENTS STATS",{delegatedHandlersCount1:t,delegatedHandlersCount2:r,delegatedEventTypesCount:i,delegationRegistriesCount:n,delegationElementsCount:o,documentListenersCount:e})}))},2916:(e,t,n)=>{n.d(t,{Z:()=>w});var r=n(4050),o=n(6926),d=n(3716),a=n(5247),u=n(782);const i=new Set(["key","ref","teactFastList","teactOrderKey"]),s=new Set(["dir","role"]),c={autoPlay:"autoplay",autoComplete:"autocomplete"},l={};function f(e,t,n,o,a){let{skipComponentUpdate:u=!1,forceIndex:i=!1,fragment:s,moveDirection:c}=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{};const l=t&&(0,r.op)(t),f=n&&(0,r.op)(n);if(!u&&l&&f&&!(0,r.k)(t,n)&&(n=m(t,n)),!u&&f&&n.componentInstance.isMounted&&p(n,o,a,e),t===n)return n;if(d.eM&&n){const e=(0,r.U9)(n);if(e&&(!t||e!==(0,r.U9)(t)))throw new Error("[Teact] Cached virtual element was moved within tree")}if(!t&&n){f&&(n=h(n,o,a,e));const t=g(n);(0,r.CD)(n,t),i&&e.childNodes[a]?e.insertBefore(t,e.childNodes[a]):(s||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)){f&&(n=h(n,o,a,e));const d=g(n);(0,r.CD)(n,d),e.replaceChild(d,(0,r.U9)(t)),(0,r.Zb)(t)}else{const o=l&&f,d=(0,r.U9)(t);if(o||((0,r.CD)(n,d),(0,r.CD)(t,void 0),"props"in t&&"props"in n&&(n.props.ref=t.props.ref)),(0,r.O_)(n)){if(c){const t=d,n=e.childNodes["up"===c?a:a+1];n?e.insertBefore(t,n):(s||e).appendChild(t)}o||b(t,n,d),n.children=v(t,n,o?e:d)}}return n}function h(e,t,n,o){if(!(0,r.op)(e))return e;const{componentInstance:d}=e;if(!d.isMounted){p(e=(0,r.Hb)(d),t,n,o);const a=e.children[0];(0,r.op)(a)&&(e.children=[h(a,e,0,o)]),d.isMounted=!0}return e}function m(e,t){return e.componentInstance.props=t.componentInstance.props,(0,r.SO)(e.componentInstance)}function p(e,t,n,r){const{componentInstance:o}=e;o.onUpdate=()=>{t.children[n]=f(r,t.children[n],o.$element,t,n,{skipComponentUpdate:!0})}}function g(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 g(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.entries(n).forEach((e=>{let[t,r]=e;void 0!==n[t]&&I(d,t,r)})),e.children=o.map(((t,n)=>f(d,void 0,t,e,n))),d}function v(e,t,n){if(d.eM&&function(e){const t=e[0];if(t&&"props"in t&&void 0!==t.props.key){const t=e.reduce(((e,t)=>("props"in t&&t.props.key&&e.push(t.props.key),e)),[]);if(t.length!==(0,u.Tw)(t).length)throw new Error("[Teact] Children keys are not unique")}}(t.children),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 a=0;const u=e.children.reduce(((e,r,d)=>{let u="props"in r?r.props.key:void 0;const i=null!=u;if(i&&!o.has(u))return f(n,r,void 0,t,-1),e;if(!i){const o=t.children[d],a=o&&"props"in o?o.props.key:void 0;if(!o||a)return f(n,r,void 0,t,-1),e;u=`__indexKey#${d}`}return e[u]={$element:r,index:a++,order:"props"in r?r.props.teactOrderKey:void 0},e}),{});let i,s,c=[],l=0;return t.children.forEach(((e,r)=>{const o="props"in e?e.props.key:`__indexKey#${r}`,d=u[o];if(!d)return i||(i=[],s=r),void i.push(e);i&&(c=c.concat(y(i,s,n,t)),s=void 0,i=void 0);const a="props"in e?e.props.teactOrderKey:void 0,h=d.index!==l&&d.order!==a,m=h&&l>d.index;h&&!m||l++,c.push(f(n,d.$element,e,t,r,{forceIndex:!0,moveDirection:h?m?"down":"up":void 0}))})),i&&(c=c.concat(y(i,s,n,t))),c}(e,t,n);const o=e.children.length,a=t.children.length,i=Math.max(o,a),s=[],c=a>o+1?document.createDocumentFragment():void 0;for(let r=0;r=o?{fragment:c}:void 0);d&&s.push(d)}return c&&n.appendChild(c),s}function y(e,t,n,r){if(1===e.length)return[f(n,void 0,e[0],r,t,{forceIndex:!0})];if(e.length>1){const o=document.createDocumentFragment(),d=e.map((e=>f(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 b(e,t,n){const r=Object.entries(e.props),o=Object.entries(t.props);r.forEach((e=>{let[r,o]=e;const 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,a.xg)(e,t,n,t.endsWith("Capture")):t.startsWith("data-")||t.startsWith("aria-")||s.has(t)?e.removeAttribute(t):i.has(t)||delete e[c[t]||t]}(n,r,o)})),o.forEach((t=>{let[r,o]=t;const d=e.props[r];void 0!==o&&o!==d&&I(n,r,o)}))}function I(e,t,n){"className"===t?e.className=n:"value"===t?e.value!==n&&(e.value=n):"style"===t?e.style.cssText=n:"dangerouslySetInnerHTML"===t?e.innerHTML=n.__html:t.startsWith("on")?(0,a.Oo)(e,t,n,t.endsWith("Capture")):t.startsWith("data-")||t.startsWith("aria-")||s.has(t)?e.setAttribute(t,n):i.has(t)||(e[c[t]||t]=n)}const w={render:function(e,t){if(!t)return;let n=t.getAttribute("data-teact-head-id");n||(n=(0,o.Z)(l),l[n]={children:[]},t.setAttribute("data-teact-head-id",n));const r=l[n];r.children=[f(t,r.children[0],e,r,0)]}}},4050:(e,t,n)=>{n.d(t,{CD:()=>x,Hb:()=>T,I4:()=>_,O_:()=>v,SO:()=>M,U9:()=>R,V2:()=>h,X$:()=>U,Ye:()=>Z,ZP:()=>j,Zb:()=>k,bt:()=>D,d4:()=>O,eJ:()=>B,iB:()=>m,k:()=>A,op:()=>g,sO:()=>$});var r=n(3716),o=n(9118),d=n(782),a=n(275),u=n(3592),i=n(5247);let s;!function(e){e[e.Empty=0]="Empty",e[e.Text=1]="Text",e[e.Tag=2]="Tag",e[e.Component=3]="Component"}(s||(s={}));const c=Symbol("Fragment"),l=new Set(["TeactMemoWrapper","TeactNContainer","Button","ListItem","MenuItem"]);let f;function h(e){return e.type===s.Empty}function m(e){return e.type===s.Text}function p(e){return e.type===s.Tag}function g(e){return e.type===s.Component}function v(e){return p(e)||g(e)}function y(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),o=2;o1&&void 0!==arguments[1]?arguments[1]:[];const{props:n}=e;return{componentInstance:e,type:s.Component,props:n,children:t}}function w(e,t,n){return{type:s.Tag,tag:e,props:t,children:C(n).map(E)}}function C(e){let t=e.length-1;for(;t>=0&&S(e[t]);t--);return t+17&&console.warn(`[Teact] Slow component render: ${n}, ${Math.round(t)} ms`),P[n].renderTimes.push(t),P[n].renderCount++}}catch(t){(0,u.S)(t),o=e.renderedValue}if(e.isMounted&&o===e.renderedValue)return e.$element;e.renderedValue=o;const d=E(o);return e.$element=I(e,[d]),e.$element}function A(e,t){return typeof e!=typeof t||e.type!==t.type||(m(e)&&m(t)?e.value!==t.value:p(e)&&p(t)?e.tag!==t.tag||e.props.key!==t.props.key:!(!g(e)||!g(t)||e.componentInstance.Component===t.componentInstance.Component&&e.props.key===t.props.key))}function k(e){if(g(e))(t=e.componentInstance).isMounted&&(t.hooks.memos.byCursor.forEach((e=>{e.current=void 0})),t.hooks.effects.byCursor.forEach((e=>{let{cleanup:t}=e;if("function"==typeof t)try{t()}catch(e){(0,u.S)(e)}})),t.isMounted=!1,function(e){e.hooks.effects.byCursor.forEach((e=>{e.cleanup=void 0,e.effect=void 0,e.dependencies=void 0})),e.hooks.state.byCursor.forEach((e=>{e.value=void 0,e.nextValue=void 0,e.setter=void 0})),e.hooks.memos.byCursor.forEach((e=>{e.dependencies=void 0})),e.hooks=void 0,e.$element=void 0,e.renderedValue=void 0,e.Component=void 0,e.props=void 0,e.forceUpdate=void 0,e.onUpdate=void 0}(t));else if(p(e)&&(e.target&&(0,i.lQ)(e.target),e.props.ref&&(e.props.ref.current=void 0)),e.target&&(e.target=void 0),!v(e))return;var t;e.children.forEach(k)}function T(e){return M(e),e.isMounted=!0,e.$element}function N(e){e.isMounted&&(e.hooks.state.byCursor.forEach((e=>{e.value=e.nextValue})),e.prepareForFrame=(0,o.wT)((()=>N(e))),e.forceUpdate=(0,o.mS)((()=>L(e))))}function L(e){if(!e.isMounted||!e.onUpdate)return;const t=e.$element;M(e),e.$element!==t&&e.onUpdate()}function R(e){if(g(e)){const t=e.children[0];return t?R(t):void 0}return e.target}function x(e,t){g(e)?x(e.children[0],t):e.target=t}function B(e){const{cursor:t,byCursor:n}=f.hooks.state;var d;return void 0===n[t]&&(n[t]={value:e,nextValue:e,setter:(d=f,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)((()=>N(d))),d.forceUpdate=(0,o.mS)((()=>L(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))})}),f.hooks.state.cursor++,[n[t].value,n[t].setter]}function F(e,t,n,o,d){const{cursor:a,byCursor:i}=f.hooks.effects,s=f;function c(){if(!s.isMounted)return;const{cleanup:e}=i[a];if("function"==typeof e)try{let t;if(r.eM&&(t=performance.now()),e(),r.eM){const e=performance.now()-t,n=s.name;e>7&&console.warn(`[Teact] Slow cleanup at effect cursor #${a}: ${n}, ${Math.round(e)} ms`)}}catch(e){(0,u.S)(e)}}function l(){if(!s.isMounted)return;let e;if(r.eM&&(e=performance.now()),i[a].cleanup=n(),r.eM){const t=performance.now()-e,n=s.name;t>7&&console.warn(`[Teact] Slow effect at cursor #${a}: ${n}, ${Math.round(t)} ms`)}}if(void 0!==i[a]&&o&&i[a].dependencies){if(o.some(((e,t)=>e!==i[a].dependencies[t]))){if(d){const e=o.reduce(((e,t,n)=>{const r=i[a].dependencies[n];return t!==r&&e.push(`${n}: ${r} => ${t}`),e}),[]);console.log(`[Teact] Effect "${d}" caused by dependencies.`,e.join(", "))}t(c),e(l)}}else d&&console.log(`[Teact] Effect "${d}" caused by missing dependencies.`),t(c),e(l);i[a]={effect:n,dependencies:o,cleanup:i[a]?i[a].cleanup:void 0},f.hooks.effects.cursor++}function O(e,t,n){return F(o.T2,o.D0,e,t,n)}function D(e,t,n){return F(o.R3,o.zD,e,t,n)}function Z(e,t,n){const{cursor:o,byCursor:d}=f.hooks.memos;let{current:u}=d[o]||{};return(void 0===d[o]||t.some(((e,t)=>e!==d[o].dependencies[t])))&&(r.eM&&n&&console.log(`[Teact.useMemo] ${f.name} (${n}): Update is caused by:`,d[o]?(0,a.c)(t,d[o].dependencies).join(", "):"[first render]"),u=e()),d[o]={current:u,dependencies:t},f.hooks.memos.cursor++,u}function _(e,t,n){return Z((()=>e),t,n)}function $(e){return Z((()=>({current:e})),[])}function U(e,t){return function(n){return Z((()=>y(e,n)),Object.values(n),t)}}document.addEventListener("dblclick",(()=>{console.warn("COMPONENTS",(0,d.Xo)(Object.values(P),"renderCount","desc"))}));const j={createElement:y,Fragment:c}},5116:(e,t,n)=>{n.d(t,{Iq:()=>P,Rd:()=>w,gP:()=>A,ll:()=>E});var r=n(4050),o=n(3716),d=n(5326),a=n(6926),u=n(9118),i=n(275),s=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`)}}],g={},v=new Map,y=(0,u.$6)(b);function b(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];e||!(0,l.zG)()?p.forEach((e=>e(h))):(0,u.T2)(y)}function I(e,t){"object"==typeof e&&e!==h&&(h=e,null!=t&&t.forceSyncOnIOs?b(!0):y(null==t?void 0:t.forceOnHeavyAnimation))}function w(){return h}function C(){return g}function S(e,t){m[e]||(m[e]=[],g[e]=(t,n)=>{!function(e,t,n){var r;null===(r=m[e])||void 0===r||r.forEach((e=>{const r=e(h,g,t);r&&("function"==typeof r.then?r.then((e=>{e&&I(e,n)})):I(r,n))}))}(e,t,n)}),m[e].push(t)}function E(e){p.push(e)}function P(e){const t=p.indexOf(e);-1!==t&&p.splice(t,1)}function M(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:()=>({});return t=>function n(o){n.DEBUG_contentComponentName=t.name;const[u]=(0,r.eJ)((0,a.Z)(v)),s=(0,d.Z)();(0,r.d4)((()=>()=>{v.delete(u)}),[u]);let l=v.get(u);if(l||(l={mapStateToProps:e,ownProps:o,areMappedPropsChanged:!1,forceUpdate:s,DEBUG_updates:0,DEBUG_componentName:t.name},v.set(u,l)),l.areMappedPropsChanged&&(l.areMappedPropsChanged=!1),!l.mappedProps||!(0,i.Z)(l.ownProps,o)){l.ownProps=o;try{l.mappedProps=e(h,o)}catch(e){(0,c.S)(e)}}return r.ZP.createElement(t,f({},l.mappedProps,o))}}function A(){return{getGlobal:w,setGlobal:I,getActions:C,addActionHandler:S,withGlobal:M}}o.eM&&(window.getGlobal=w,document.addEventListener("dblclick",(()=>{console.warn("GLOBAL CONTAINERS",(0,s.Xo)(Array.from(v.values()).map((e=>{let{DEBUG_componentName:t,DEBUG_updates:n}=e;return{DEBUG_componentName:t,DEBUG_updates:n}})),"DEBUG_updates","desc"))})))},3681:(e,t,n)=>{n.d(t,{Z:()=>a,l:()=>d});const r=/\uFE0F/g,o=String.fromCharCode(8205);function d(e){return e.indexOf(o)<0?e.replace(r,""):e}const a=/(?:\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},1713:(e,t,n)=>{let r,o,d,a,u,i,s,c,l,f,h,m,p,g;n.d(t,{Cr:()=>c,KB:()=>g,MT:()=>d,Nh:()=>l,Uq:()=>r,WB:()=>m,bZ:()=>s,du:()=>a,fo:()=>o,mp:()=>v,nJ:()=>u,qt:()=>i,rN:()=>f,u1:()=>y,vi:()=>p,wv:()=>h}),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",e[e.QuickReaction=50]="QuickReaction"}(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"}(a||(a={})),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"}(u||(u={})),function(e){e[e.ChatInfo=0]="ChatInfo",e[e.Search=1]="Search",e[e.Management=2]="Management",e[e.Statistics=3]="Statistics",e[e.StickerSearch=4]="StickerSearch",e[e.GifSearch=5]="GifSearch",e[e.PollResults=6]="PollResults",e[e.AddingMembers=7]="AddingMembers"}(i||(i={})),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"}(s||(s={})),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",e[e.ConfirmPayment=4]="ConfirmPayment"}(g||(g={}));const v="UPLOADING_WALLPAPER_SLUG";let y;!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.ChannelRemovedUsers=7]="ChannelRemovedUsers",e[e.GroupUserPermissionsCreate=8]="GroupUserPermissionsCreate",e[e.GroupUserPermissions=9]="GroupUserPermissions",e[e.ChatAdministrators=10]="ChatAdministrators",e[e.GroupRecentActions=11]="GroupRecentActions",e[e.ChatAdminRights=12]="ChatAdminRights",e[e.ChatNewAdminRights=13]="ChatNewAdminRights",e[e.GroupMembers=14]="GroupMembers",e[e.GroupAddAdmins=15]="GroupAddAdmins",e[e.Invites=16]="Invites",e[e.EditInvite=17]="EditInvite",e[e.Reactions=18]="Reactions",e[e.InviteInfo=19]="InviteInfo",e[e.JoinRequests=20]="JoinRequests"}(y||(y={}))},9933:(e,t,n)=>{n.d(t,{M8:()=>u,cK:()=>d,jt:()=>a,vr:()=>i});var r=n(9118);let o;function d(e,t){t||(o&&!o.isCancelled&&(o.isCancelled=!0),o=t={isCancelled:!1}),!t.isCancelled&&e()&&(0,r.T2)((()=>{d(e,t)}))}function a(e){e()&&(0,r.T2)((()=>{a(e)}))}const u={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 i(e){let{timing:t=u.linear,onUpdate:n,duration:r,onEnd:o,from:d,to:i}=e;const s=Date.now();let c=!1;return a((()=>{if(c)return!1;let e=(Date.now()-s)/r;e>1&&(e=1);const a=t(e);if("number"==typeof d&&"number"==typeof i)n(d+(i-d)*a);else if(Array.isArray(d)&&Array.isArray(i)){const e=d.map(((e,t)=>e+(i[t]-e)*a));n(e)}return 1===e&&o&&o(),e<1})),()=>{c=!0,o&&o()}}},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)=>{function r(){for(var e=arguments.length,t=new Array(e),n=0;n1?r-1:0),d=1;d(t&&(Array.isArray(t)?e.push(...t):e.push(`${n}--${t}`)),e)),[n]).join(" ")}}n.d(t,{Z:()=>r,y:()=>o})},9524:(e,t,n)=>{n.d(t,{Type:()=>o,clear:()=>u,fetch:()=>d,save:()=>a});const r=self.caches;let o;async function d(e,t,n){let d=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(r)try{const a=new Request(t.replace(/:/g,"_")),u=await r.open(e),i=await u.match(a);if(!i)return;const s=i.headers.get("Content-Type");switch(n){case o.Text:return await i.text();case o.Blob:{if(t.startsWith("avatar")&&s&&s.startsWith("text"))return;const e=await i.blob(),n=!e.type||!d&&e.type.includes("html");let r=e.type||s;return n&&r?(d||(r=r.replace(/html/gi,"")),new Blob([e],{type:r})):e}case o.Json:return await i.json();default:return}}catch(e){return void console.warn(e)}}async function a(e,t,n){if(r)try{const o="string"==typeof n||n instanceof Blob?n:JSON.stringify(n),d=new Request(t.replace(/:/g,"_")),a=new Response(o),u=await r.open(e);return await u.put(d,a)}catch(e){return void console.warn(e)}}async function u(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={}))},6063:(e,t,n)=>{function r(){const e=[];function t(t){const n=e.indexOf(t);-1!==n&&e.splice(n,1)}return{runCallbacks:function(){for(var t=arguments.length,n=new Array(t),r=0;r{e(...n)}))},addCallback:function(n){return e.push(n),()=>{t(n)}},removeCallback:t,hasCallbacks:function(){return Boolean(e.length)}}}n.d(t,{_:()=>r})},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 a()||document.addEventListener("keydown",u,!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)}})),a()||document.removeEventListener("keydown",u,!1)}(e)}}function a(){return Object.values(o).some((e=>Boolean(e.length)))}function u(e){const t=r[e.key];if(!t)return;const{length:n}=o[t];n&&(e.stopPropagation(),(0,o[t][n-1])(e))}},4319:(e,t,n)=>{n.d(t,{TE:()=>a,VP:()=>u,yl:()=>o});var r=n(3716);const o=window.navigator.clipboard&&window.ClipboardItem,d=document.createElement("textarea");d.setAttribute("readonly",""),d.tabIndex=-1,d.className="visually-hidden";const a=e=>{d.value=e,document.body.appendChild(d);const t=document.getSelection();if(t){const e=t.rangeCount>0&&t.getRangeAt(0);d.select(),document.execCommand("copy"),e&&(t.removeAllRanges(),t.addRange(e))}document.body.removeChild(d)},u=e=>{if(!e)return;const t=document.createElement("canvas"),n=t.getContext("2d"),r=new Image;r.onload=e=>{if(n&&e.currentTarget){const r=e.currentTarget;t.width=r.width,t.height=r.height,n.drawImage(r,0,0,r.width,r.height),t.toBlob(i,"image/png",1)}},r.src=e};async function i(e){if(e&&o)try{var t,n;await(null===(t=(n=window.navigator.clipboard).write)||void 0===t?void 0:t.call(n,[new ClipboardItem({[e.type]:e})]))}catch(e){r.eM&&console.error(e)}}},790:(e,t,n)=>{n.d(t,{$Y:()=>s,D:()=>v,IS:()=>N,SA:()=>A,Tu:()=>p,VX:()=>m,ZK:()=>C,_F:()=>c,dJ:()=>b,j1:()=>I,k9:()=>S,kj:()=>l,mB:()=>y,mr:()=>h,np:()=>g,rM:()=>E,xH:()=>M,xR:()=>u,xk:()=>T,zk:()=>i});var r=n(5155);const o=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],d=["January","February","March","April","May","June","July","August","September","October","November","December"],a=d.map((e=>e.toLowerCase())),u=864e5;function i(e){return c(new Date)===c(e)}function s(e){const t=new Date(e);return t.setHours(0,0,0,0),t}function c(e){return s(e).getTime()}function l(e){const t=new Date(1e3*e);return`${t.getFullYear()}-${t.getMonth()}`}function f(e){return`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`}function h(e,t){const n="number"==typeof t?new Date(t):t,r=e.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 m(e,t){const n="number"==typeof t?new Date(t):t,r=s(new Date);if(n>=r)return h(e,n);const d=new Date(r);if(d.setDate(r.getDate()-7),n>=d)return e(`Weekday.Short${o[n.getDay()]}`);const a=n.getFullYear()!==r.getFullYear(),u=e(a?"formatDateScheduleYear":"formatDateSchedule")||(a?"d MMM yyyy":"d MMM");return w(e,n,u)}function p(e,t){const n="number"==typeof t?new Date(t):t,r=e("formatterYearMax")||"dd.MM.yyyy";return w(e,n,r)}function g(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const r=e(n?"formatterMonthYear2":"formatterMonthYear")||"MMM yyyy";return w(e,t,r)}function v(e,t){const n=Math.floor(t/u);return t<0?0:n<1?S(t/1e3):n<7?e("Days",n):n<30?e("Weeks",Math.floor(n/7)):n<365?e("Months",Math.floor(n/30)):e("Years",Math.floor(n/365))}function y(e,t){return t<6e4?Math.ceil(t/1e3):t<36e5?Math.ceil(t/6e4):t2&&void 0!==arguments[2]?arguments[2]:t;const r=t-n;return r<60?e("LiveLocationUpdated.JustNow"):r<3600?e("LiveLocationUpdated.MinutesAgo",Math.floor(r/60)):e("LiveLocationUpdated.TodayAt",h(e,n))}function I(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],d=arguments.length>4?arguments[4]:void 0;const a="number"==typeof t?new Date(t):t,u=s(new Date);if(!r){if(f(a)===f(u))return(d||!n?R:L)(e("Weekday.Today"));const t=new Date(u);if(t.setDate(u.getDate()-1),f(a)===f(t))return(d||!n?R:L)(e("Weekday.Yesterday"));const r=new Date(u),i=new Date(u);if(r.setDate(u.getDate()-7),i.setDate(u.getDate()+7),a>=r&&a<=i){const t=o[a.getDay()];return(d||!n?R:L)(e(n?`Weekday.Short${t}`:`Weekday.${t}`))}}const i=a.getFullYear()!==u.getFullYear(),c=n?i?"formatDateScheduleYear":"formatDateSchedule":i?"chatFullDate":"chatDate",l=e(c)||"d MMMM yyyy";return(d||!n?R:L)(w(e,a,l))}function w(e,t,n){const r=t.getDate(),o=t.getMonth();return n.replace("LLLL",e(d[o])).replace("MMMM",e(`Month.Gen${d[o]}`)).replace("MMM",e(`Month.Short${d[o]}`)).replace("MM",String(o+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 C(e,t,n){const r="number"==typeof t?new Date(t):t;return`${I(e,r,!0,void 0,n)}, ${h(e,r)}`}function S(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,a=t?Math.floor(t%3600/60):0;let u="";return n>0||d>0?(u+=`${String(n).padStart(2,"0")}:`,u+=`${String(r).padStart(2,"0")}:`):u+=a>=10?`${String(r).padStart(2,"0")}:`:`${String(r)}:`,u+=String(o).padStart(2,"0"),u}function E(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")}`}const P=(0,r.Z)(((e,t)=>new Date(e).toLocaleString(t,{year:"numeric",month:"short",day:"numeric"})));function M(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"en-US";const n="number"==typeof e?new Date(e):e,r=c(n);return P(r,t)}function A(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"en-US";const n="number"==typeof e?new Date(e):e;return n.toLocaleString(t,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})}function k(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:2021;if(t>11||e>31)return!1;const r=new Date(n,t,e);return!Number.isNaN(r.getTime())&&r.getDate()===e}function T(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";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||!k(t,n-1,r||void 0)?void 0:`${r?`${r}-`:""}${String(n).padStart(2,"0")}-${String(t).padStart(2,"0")}`}const o=e.split(" "),d=t?o[0]:o[1],u=(t?o[1]:o[0]).toLowerCase(),i=a.findIndex((e=>e.startsWith(u)));return-1!==i&&k(Number(d),i)?`${String(i+1).padStart(2,"0")}-${String(d).padStart(2,"0")}`:void 0}function N(e){return e+u/1e3}function L(e){return`${e[0].toLowerCase()}${e.slice(1)}`}function R(e){return`${e[0].toUpperCase()}${e.slice(1)}`}},4284:(e,t,n)=>{n.d(t,{NM:()=>s,U_:()=>i,Wg:()=>c,g6:()=>u});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 a(e){const t=e.split("-").map((e=>parseInt(e,16)));return String.fromCodePoint(...t)}function u(e){if(!e.match(r.Z))return e;for(const[t,n]of d)e=e.replace(t,n);return e}function i(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 s(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:()=>x,wZ:()=>p,gk:()=>F,vX:()=>M,FW:()=>O,op:()=>C,cj:()=>m,jm:()=>h,pA:()=>L,m5:()=>P,I_:()=>E,fl:()=>v,t0:()=>A,s$:()=>g,i4:()=>D,Mc:()=>S,wB:()=>b,p7:()=>I,$b:()=>y,mh:()=>w,Hh:()=>R,s0:()=>T,aZ:()=>B,gZ:()=>Z,Lt:()=>f,vn:()=>s,on:()=>d});var r=n(3716);let o;function d(){return Boolean(o)}var a,u;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 i=null!==(a=(u=window).matchMedia)&&void 0!==a&&a.call(u,"(prefers-color-scheme: dark)").matches?"dark":"light";function s(){return i}function c(e){i=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),v=window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone||document.referrer.includes("android-app://"),y=window.matchMedia("(pointer: coarse)").matches,b=window.innerWidth<=r.l3||window.innerWidth<=r.u_&&window.innerHeight<=r.rO,I=!b&&window.innerWidth<=r.ks,w=Boolean(window.navigator.mediaDevices&&"getUserMedia"in window.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=!0;L&&r.wG.add(r.Ng);const R=Boolean(N.canPlayType('video/webm; codecs="vp9"').replace("no",""))&&!(h&&g),x=window.devicePixelRatio||1,B=!0,F=!r.Cg&&(CSS.supports("backdrop-filter: blur()")||CSS.supports("-webkit-backdrop-filter: blur()")),O=!y,D=!h&&!m&&!p,Z=D?300:750},1394:(e,t,n)=>{n.d(t,{A9:()=>d,YJ:()=>a,ao:()=>h,dc:()=>f,gm:()=>l,hl:()=>u,jj:()=>s,pt:()=>i,ud:()=>c});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 a(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 u(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}function i(e){return new Promise(((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=n,r.src=e}))}function s(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 s(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 u(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}})},6974:(e,t,n)=>{n.d(t,{M2:()=>P,O6:()=>A,S1:()=>b,Yz:()=>C,aE:()=>w,gO:()=>I,r_:()=>M,wC:()=>S,xW:()=>E});var r=n(5116),o=n(3555),d=n(3716),a=n(1192),u=n(5806),i=n(9118),s=n(782),c=n(275),l=n(6063);const f=R();let h=f.prevGlobal,m=f.prepared,p=f.results,g=f.callbacks;const v=(0,i.P2)((()=>{(0,i.Q8)((()=>{k((0,o.Rd)())}))}),500);let y=!1;function b(){y=!0,(0,r.ll)(v),(0,o.iw)("reset",x),k((0,o.Rd)())}function I(e){return y||b(),p.orderedIdsByFolderId[e]}function w(e){return y||b(),p.pinnedCountByFolderId[e]||0}function C(){return y||b(),p.chatsCountByFolderId}function S(){return y||b(),p.unreadCountersByFolderId}function E(){var e;return(null===(e=S()[d.Nf])||void 0===e?void 0:e.notificationsCount)||0}function P(e,t){return g.orderedIdsByFolderId[e]||(g.orderedIdsByFolderId[e]=(0,l._)()),g.orderedIdsByFolderId[e].addCallback(t)}function M(e){return g.chatsCountByFolderId.addCallback(e)}function A(e){return g.unreadCountersByFolderId.addCallback(e)}function k(e){let t;d.eM&&(t=performance.now());const n=Boolean(e.chats.listIds.active&&T(d.Nf,e.chats.listIds.active,e.chats.orderedPinnedIds.active)),r=Boolean(e.chats.listIds.archived&&T(d.WS,e.chats.listIds.archived,e.chats.orderedPinnedIds.archived)),o=e.chats.isFullyLoaded.active!==h.isAllFolderFullyLoaded,i=e.chats.isFullyLoaded.archived!==h.isArchivedFolderFullyLoaded,l=e.chatFolders.byId!==h.foldersById,f=e.chats.byId!==h.chatsById,g=e.users.byId!==h.usersById,v=(0,a.dZ)(e)!==h.notifySettings,y=(0,a.NJ)(e)!==h.notifyExceptions;let b=[];if((o||i)&&(b=b.concat(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=[];t&&n.push(d.WS);const r=e.chats.isFullyLoaded.active,o=e.chats.isFullyLoaded.archived;if(r&&o){const e=Object.keys(m.folderSummariesById).filter((e=>!p.orderedIdsByFolderId[e])).map(Number);n=n.concat(e)}return h.isAllFolderFullyLoaded=r,h.isArchivedFolderFullyLoaded=o,n}(e,i))),!(n||r||l||f||g||v||y))return void(b.length&&L(b));const I=h.allFolderListIds,w=h.archivedFolderListIds;if(function(e,t,n,r){const o=[];if(t){const t=e.chats.listIds.active,n=e.chats.orderedPinnedIds.active;m.folderSummariesById[d.Nf]=N(d.Nf,t,n),h.allFolderListIds=t,h.allFolderPinnedIds=n,o.push(d.Nf)}if(n){const t=e.chats.listIds.archived,n=e.chats.orderedPinnedIds.archived;m.folderSummariesById[d.WS]=N(d.WS,t,n),h.archivedFolderListIds=t,h.archivedFolderPinnedIds=n,o.push(d.WS)}if(r){const t=e.chatFolders.byId;Object.values(t).forEach((e=>{e!==h.foldersById[e.id]&&(m.folderSummariesById[e.id]=function(e){return{...e,orderedPinnedIds:e.pinnedChatIds,excludedChatIds:e.excludedChatIds?new Set(e.excludedChatIds):void 0,includedChatIds:e.excludedChatIds?new Set(e.includedChatIds):void 0,pinnedChatIds:e.excludedChatIds?new Set(e.pinnedChatIds):void 0}}(e),o.push(e.id))})),h.foldersById=t}}(e,n,r,l),b=b.concat(function(e,t,n,r,o,i){const l=e.chats.byId,f=e.users.byId,g=(0,a.dZ)(e),v=(0,a.NJ)(e),y=Object.values(m.folderSummariesById),b=new Set,I=e.chats.listIds.active,w=e.chats.listIds.archived;let C=[...I||[],...w||[]];return I===o&&w===i||(C=(0,s.Tw)(C.concat(o||[],i||[]))),C.forEach((e=>{const o=l[e];if(!t&&!n&&!r&&o===h.chatsById[e]&&f[e]===h.usersById[e])return;let a;if(o){const n=m.chatSummariesById.get(e),r=function(e,t,n,r){const{id:o,type:a,lastMessage:i,isRestricted:s,isNotJoined:c,folderId:l,unreadCount:f,unreadMentionsCount:h,hasUnreadMark:m,joinDate:p,draftDate:g}=e,v="chatTypePrivate"===a&&r;return{id:o,type:a,isListed:Boolean(i&&!s&&!c),isArchived:l===d.WS,isMuted:(0,u.i4)(e,t,n),isUnread:Boolean(f||h||m),unreadCount:f,unreadMentionsCount:h,order:Math.max(p||0,g||0,(null==i?void 0:i.date)||0),isUserBot:v?"userTypeBot"===v.type:void 0,isUserContact:v?v.isContact:void 0}}(o,g,v,f[e]);if(!t&&n&&(0,c.Z)(r,n))return;m.chatSummariesById.set(e,r),a=function(e,t){return t.reduce(((t,n)=>(function(e,t){var n,r,o;if(!e.isListed)return!1;const{id:a,type:u}=e;if(t.listIds)return!(e.isArchived&&t.id===d.Nf||!e.isArchived&&t.id===d.WS)&&t.listIds.has(a);if(null!==(n=t.excludedChatIds)&&void 0!==n&&n.has(a))return!1;if(null!==(r=t.includedChatIds)&&void 0!==r&&r.has(a))return!0;if(null!==(o=t.pinnedChatIds)&&void 0!==o&&o.has(a))return!0;if(t.excludeArchived&&e.isArchived)return!1;if(t.excludeRead&&!e.isUnread)return!1;if(t.excludeMuted&&e.isMuted&&!e.unreadMentionsCount)return!1;if("chatTypePrivate"===u)if(e.isUserBot){if(t.bots)return!0}else{if(t.contacts&&e.isUserContact)return!0;if(t.nonContacts&&!e.isUserContact)return!0}else{if("chatTypeChannel"===u)return Boolean(t.channels);if("chatTypeBasicGroup"===u||"chatTypeSuperGroup"===u)return Boolean(t.groups)}return!1}(e,n)&&t.push(n.id),t)),[]).sort()}(r,y),a.forEach((e=>{b.add(e)}))}else m.chatSummariesById.delete(e),a=[];const i=m.folderIdsByChatId[e]||[];if((0,s.et)(a,i))return;const I=function(e,t,n){const r=new Set(t),o=new Set(n),d=[];return(0,s.Tw)([...t,...n]).forEach((t=>{let n=p.orderedIdsByFolderId[t];r.has(t)&&!o.has(t)?(m.chatIdsByFolderId[t].delete(e),d.push(t),n&&(n=n.filter((t=>t!==e)),m.isOrderedListJustPatched[t]=!0)):!r.has(t)&&o.has(t)&&(m.chatIdsByFolderId[t]||(m.chatIdsByFolderId[t]=new Set),m.chatIdsByFolderId[t].add(e),n&&(n.push(e),m.isOrderedListJustPatched[t]=!0)),p.orderedIdsByFolderId[t]=n})),m.folderIdsByChatId[e]=n,d}(e,i,a);I.forEach((e=>{b.add(e)}))})),h.chatsById=l,h.usersById=f,h.notifySettings=g,h.notifyExceptions=v,Array.from(b)}(e,l||n||r,v,y,I,w)),L((0,s.Tw)(b)),d.eM){const e=performance.now()-t;e>6&&console.warn(`Slow \`updateFolderManager\`: ${Math.round(e)} ms`)}}function T(e,t,n){const r=e===d.Nf?h.allFolderListIds:h.archivedFolderListIds,o=e===d.Nf?h.allFolderPinnedIds:h.archivedFolderPinnedIds;return r!==t||o!==n}function N(e,t,n){return{id:e,listIds:new Set(t),orderedPinnedIds:n,pinnedChatIds:new Set(n)}}function L(e){let t=!1,n=!1;if(Array.from(e).forEach((e=>{const{pinnedCount:r,orderedIds:o}=function(e){const t=m.folderSummariesById[e];if(!t)return{};const{orderedPinnedIds:n,pinnedChatIds:r}=t,{chatSummariesById:o,chatIdsByFolderId:{[e]:d}}=m,{orderedIdsByFolderId:{[e]:a}}=p,u=d?null==n?void 0:n.filter((e=>d.has(e))):n,i=a||d&&Array.from(d)||[],s=(r?i.filter((e=>!r.has(e))):i).sort(((e,t)=>o.get(t).order-o.get(e).order));return{pinnedCount:(null==u?void 0:u.length)||0,orderedIds:[...u||[],...s]}}(e);if(!o)return;const d=p.orderedIdsByFolderId[e],a=p.pinnedCountByFolderId[e];var u;d&&void 0!==a&&a===r&&!m.isOrderedListJustPatched[e]&&(0,s.et)(o,d)||(m.isOrderedListJustPatched[e]=!1,p.orderedIdsByFolderId[e]=o,p.pinnedCountByFolderId[e]=r,null===(u=g.orderedIdsByFolderId[e])||void 0===u||u.runCallbacks(o));const i=p.chatsCountByFolderId[e],l=o.length;n||(n=i!==l),p.chatsCountByFolderId[e]=l;const f=p.unreadCountersByFolderId[e],h=function(e){const{chatSummariesById:t}=m,{orderedIdsByFolderId:{[e]:n}}=p;return n.reduce(((e,n)=>{const r=t.get(n);return r?(r.isUnread&&(e.chatsCount++,r.unreadMentionsCount&&(e.notificationsCount+=r.unreadMentionsCount),r.isMuted||(r.unreadCount?e.notificationsCount+=r.unreadCount:r.unreadMentionsCount||(e.notificationsCount+=1))),e):e}),{chatsCount:0,notificationsCount:0})}(e);t||(t=!f||!(0,c.Z)(h,f)),p.unreadCountersByFolderId[e]=h})),n){const e={...p.chatsCountByFolderId};p.chatsCountByFolderId=e,g.chatsCountByFolderId.runCallbacks(e)}if(t){const e={...p.unreadCountersByFolderId};p.unreadCountersByFolderId=e,g.unreadCountersByFolderId.runCallbacks(e)}}function R(){return{prevGlobal:{foldersById:{},chatsById:{},usersById:{},notifySettings:{},notifyExceptions:{}},prepared:{folderSummariesById:{},chatSummariesById:new Map,folderIdsByChatId:{},chatIdsByFolderId:{},isOrderedListJustPatched:{}},results:{orderedIdsByFolderId:{},pinnedCountByFolderId:{},chatsCountByFolderId:{},unreadCountersByFolderId:{}},callbacks:{orderedIdsByFolderId:{},chatsCountByFolderId:(0,l._)(),unreadCountersByFolderId:(0,l._)()}}}function x(){const e=R();h=e.prevGlobal,m=e.prepared,p=e.results,g=e.callbacks}},9937:(e,t,n)=>{function r(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"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,{J_:()=>a,ZP:()=>d});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. Streaming media may not be supported. Try reloading 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",BOT_PRECHECKOUT_TIMEOUT:"The request for payment has expired"},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 a(e){return o[e.message]}},3592:(e,t,n)=>{n.d(t,{S:()=>d}),n(3716);var r=n(9118);function o(e){e instanceof ErrorEvent&&"ResizeObserver loop limit exceeded"===e.message||(e.preventDefault(),d(e instanceof ErrorEvent?e.error||e.message: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 a(e,t){return t.reduce(((t,n)=>(e[n]&&(t[n]=e[n]),t)),{})}function u(e,t){const n=new Set(t.map(String));return d(e,Object.keys(e).filter((e=>!n.has(e))))}function i(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"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],[a,u]=t,i="asc"===o,s="asc"===d;return e.sort(((e,t)=>r(e,t,a,i)||r(e,t,u,s)))}const o="asc"===n;return e.sort(((e,n)=>r(e,n,t,o)))}function s(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 v(e,t){let n=e.length;for(;n--;)if(t(e[n],n,e))return e[n]}n.d(t,{CE:()=>u,Q8:()=>o,Tw:()=>c,Vl:()=>p,Xh:()=>g,Xo:()=>i,YE:()=>h,dF:()=>v,eL:()=>m,ee:()=>r,ei:()=>d,et:()=>f,oA:()=>l,q0:()=>a,xH:()=>s})},711:(e,t,n)=>{n.d(t,{Pn:()=>w,i0:()=>I,ll:()=>p,m0:()=>C,qf:()=>S});var r=n(3555),o=n(3716),d=n(9524),a=n(1226),u=n(6063),i=n(2155);const s=/%\d?\$?[sdf@]/g,c=["value","zeroValue","oneValue","twoValue","fewValue","manyValue","otherValue"],l={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},f=new Map;let h,m;const{addCallback:p,removeCallback:g,runCallbacks:v}=(0,u._)();let y,b;const I=(e,t,n)=>{var r,o;if(void 0!==t){const r=Array.isArray(t)?JSON.stringify(t):t,o=f.get(`${e}_${r}_${n}`);if(o)return o}if(!h&&!m)return e;const d=(null===(r=h)||void 0===r?void 0:r[e])||(null===(o=m)||void 0===o?void 0:o[e]);return d?M(d,e,t,n):(m||E(),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,a.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)),M(n,t)}async function C(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(h&&e===y)return void(t&&t());let a=await d.fetch(o.ee,e,d.Type.Json);if(!a&&(n&&await E(),a=await P(e),!a))return;f.clear(),y=e,h=a,document.documentElement.lang=e;const{languages:u,timeFormat:i}=(0,r.Rd)().settings.byKey,s=null==u?void 0:u.find((t=>t.langCode===e));I.isRtl=Boolean(null==s?void 0:s.rtl),I.code=e,I.timeFormat=i,t&&t(),v()}function S(e){e&&e===b||(b=e,I.timeFormat=e,v())}async function E(){m||(m=(await n.e(915).then(n.bind(n,1915))).default,v())}async function P(e){const t=await(0,a.t9)("fetchLangPack",{sourceLangPacks:o.Bg,langCode:e});if(t)return await d.save(o.ee,e,t.langPack),t.langPack}function M(e,t,n,r){const d=e?e["number"==typeof n?function(e){const t=y||o.sR,n=l[t]?l[t](e):0;return c[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,i.kh)(n):n),o=Array.isArray(n)?JSON.stringify(n):n;return f.set(`${t}_${o}_${r}`,e),e}return d}},647:(e,t,n)=>{n.d(t,{cC:()=>b,he:()=>v,UV:()=>y,Iq:()=>I});var r=n(6137),o=n(3716),d=n(1226),a=n(9524),u=n(1394),i=n(7361);const s=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((e=>{let{buffer:t}=e;return t})))},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:s}),o.postMessage({command:"init",decoderSampleRate:s,outputBufferSampleRate:s}),o.postMessage({command:"decode",pages:r},[r.buffer])}))}var l=n(862);const f={[r.IU.BlobUrl]:a.Type.Blob,[r.IU.Lottie]:a.Type.Blob,[r.IU.Progressive]:void 0,[r.IU.Stream]:void 0},h=new Map,m=new Map,p=new Map,g=new Map;function v(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],d=arguments.length>3?arguments[3]:void 0,a=arguments.length>4?arguments[4]:void 0;if(t===r.IU.Progressive)return i.I_?w(e):v(e,r.IU.BlobUrl,n,d,a);if(!m.has(e)){const r=C(e,t,n).catch((e=>{o.eM&&console.warn(e)})).finally((()=>{m.delete(e),p.delete(e),g.delete(e)}));m.set(e,r)}if(d&&a){let t=p.get(e);t||(t=new Map,p.set(e,t)),t.set(a,d)}return m.get(e)}function y(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 I(e,t){const n=p.get(e);n&&n.delete(t)}function w(e){const t=`./progressive/${e}`;return h.set(e,t),Promise.resolve(t)}async function C(e,t,n){if(!o.Cy){const r=e.startsWith("avatar")?o.SG:o.lW,d=await a.fetch(r,e,f[t],n);if(d){let t=d;if("audio/ogg"!==d.type||i.m5||(t=await c(t)),"image/webp"===d.type&&!(0,i.on)()&&t){const n=await(0,l._y)(e,t);n&&(t=n)}const n=E(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"),a=S(e,n,r);g.set(e,a),(0,d.t9)("downloadMedia",{url:e,mediaFormat:t},a)})),h.set(e,r),r}const s=S(e);g.set(e,s);const m=await(0,d.t9)("downloadMedia",{url:e,mediaFormat:t,isHtmlAllowed:n},s);if(!m)throw new Error(`Failed to fetch media ${e}`);let{prepared:p,mimeType:v}=m;if("audio/ogg"===v&&!i.m5){const e=await(0,u.gm)(p);URL.revokeObjectURL(p);const t=await c(e);p=E(t),v=t.type}if("image/webp"===v&&!(0,i.on)()){const t=await(0,u.gm)(p);URL.revokeObjectURL(p);const n=await(0,l._y)(e,t);n&&(p=E(n))}return h.set(e,p),p}function S(e,t,n){const r=(o,d)=>{var a;null===(a=p.get(e))||void 0===a||a.forEach((e=>{e(o),e.isCanceled&&(r.isCanceled=!0)})),1===o&&(null==t||t.endOfStream()),d&&(null==n||n.appendBuffer(d))};return r}function E(e){return e instanceof Blob?URL.createObjectURL(e):e}i.I_&&navigator.serviceWorker.addEventListener("message",(async e=>{const{type:t,messageId:n,params:o}=e.data;if("requestPart"!==t)return;const a=await(0,d.t9)("downloadMedia",{mediaFormat:r.IU.Progressive,...o});if(!a)return;const{arrayBuffer:u,mimeType:i,fullSize:s}=a;navigator.serviceWorker.controller.postMessage({type:"partResponse",messageId:n,result:{arrayBuffer:u,mimeType:i,fullSize:s}},[u])}))},735:(e,t,n)=>{n.d(t,{D:()=>r});const r=[]},9203:(e,t,n)=>{n.d(t,{$y:()=>c,Qt:()=>f,gl:()=>d,o5:()=>l});var r=n(3716),o=n(6063);let d;!function(e){e[e.Auth=0]="Auth",e[e.Main=1]="Main",e[e.Extra=2]="Extra",e[e.Calls=3]="Calls"}(d||(d={}));const a={},u={},{addCallback:i,runCallbacks:s}=(0,o._)();async function c(e,t){if(!a[e]){switch(e){case d.Auth:a[d.Auth]=n.e(133).then(n.bind(n,1133));break;case d.Main:r.eM&&console.log(">>> START LOAD MAIN BUNDLE"),a[d.Main]=Promise.all([n.e(888),n.e(13),n.e(970),n.e(616)]).then(n.bind(n,5616));break;case d.Extra:a[d.Extra]=Promise.all([n.e(888),n.e(13),n.e(395)]).then(n.bind(n,1395));break;case d.Calls:a[d.Calls]=Promise.all([n.e(888),n.e(970),n.e(654)]).then(n.bind(n,7526))}a[e].then(s)}const o=await a[e];return u[e]||(u[e]=o),l(e,t)}function l(e,t){const n=u[e];if(n)return n[t]}const f=i},8406:(e,t,n)=>{n.d(t,{KC:()=>A,Ld:()=>E,Nz:()=>b,Vr:()=>M,q3:()=>y,r1:()=>C,rh:()=>P});var r=n(1226),o=n(6137),d=n(8005),a=n(3716),u=n(3555),i=n(5806),s=n(5406),c=n(1192),l=n(7361),f=n(711),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!!l.Mc&&("showNotification"in ServiceWorkerRegistration.prototype?"denied"===Notification.permission?(a.eM&&console.warn("[PUSH] The user has blocked push notifications."),!1):"PushManager"in window||(a.eM&&console.warn("[PUSH] Push messaging isn't supported."),!1):(a.eM&&console.warn("[PUSH] Push notifications aren't supported."),!1))}const v=new Set;async function y(e,t){if(void 0!==e&&v.has(e))return;const{notificationSoundVolume:n}=(0,c.dZ)((0,u.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",(()=>{v.add(e)}),{once:!0}),setTimeout((()=>{v.delete(e)}),3e3));try{await o.play()}catch(e){a.eM&&console.warn("[PUSH] Unable to play notification sound")}}const b=(0,m.Ds)(y,1e3,!0,!1);async function I(){"Notification"in window&&(["granted","denied"].includes(Notification.permission)||await Notification.requestPermission())}async function w(e){const t=(0,u.Rd)(),n=(0,u.Sv)();if(e)try{const t=p(e);return await(0,r.t9)("unregisterDevice",t),await e.unsubscribe(),void n.deleteDeviceToken()}catch(e){a.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 w(t)}let S=!1;async function E(){if(!g())return void await I();const e=await navigator.serviceWorker.ready;let t=await e.pushManager.getSubscription();if(function(e){const t=(0,u.Rd)();return!t.push||!e||p(e)!==t.push.deviceToken||Date.now()-t.push.subscribedAt>432e5}(t)){await w(t);try{t=await e.pushManager.subscribe({userVisibleOnly:!0});const n=p(t);a.eM&&console.log("[PUSH] Received push subscription: ",n),await(0,r.t9)("registerDevice",n),(0,u.Sv)().setDeviceToken(n)}catch(e){"denied"===Notification.permission?a.eM&&console.warn("[PUSH] The user has blocked push notifications."):a.eM&&(console.log("[PUSH] Unable to subscribe to push.",e),e.code===DOMException.ABORT_ERR&&await I())}}}async function P(e){let{chat:t,message:n,isReaction:m=!1}=e;const{hasWebNotifications:p}=await async function(){if(S)return(0,c.dZ)((0,u.Rd)());const[e,t]=await Promise.all([(0,r.t9)("fetchNotificationSettings",{serverTimeOffset:(0,u.Rd)().serverTimeOffset}),(0,r.t9)("fetchNotificationExceptions",{serverTimeOffset:(0,u.Rd)().serverTimeOffset})]);if(!e)return(0,c.dZ)((0,u.Rd)());let n=(0,s.BI)((0,u.Rd)(),e);return t&&(n=(0,s.aJ)(n,t)),(0,u.R3)(n),S=!0,(0,c.dZ)(n)}();if(!function(e){if(!S)return!1;const t=(0,u.Rd)();if((0,i.i4)(e,(0,c.dZ)(t),(0,c.NJ)(t))||e.isNotJoined||!e.isListed)return!1;if(l.$b){const{chatId:n,type:r}=(0,c.Bt)(t)||{};return!(n===e.id&&"thread"===r)}return!document.hasFocus()}(t))return;const v="Notification"in window?"denied"!==Notification.permission||(a.eM&&console.warn("[PUSH] The user has blocked push notifications."),!1):(a.eM&&console.warn("[PUSH] This browser does not support desktop notification"),!1);if(!p||!v){if(m)return;return void b(String(n.id)||t.id)}if(!v)return;if(!n.id)return;const y=(0,i.dT)(n),I=await async function(e){const t=(0,i.RT)(e);if(!t)return;let n=h.UV(t);return n||(await h.he(t,o.IU.BlobUrl),n=h.UV(t)),n}(t),{title:w,body:C}=function(e,t,n){const r=(0,u.Rd)(),{replyToMessageId:o}=t;let{senderId:a}=t;n&&(a=n.userId);const s=a?(0,c.dy)(r,a):void 0,l=(0,i.N5)(t),h=l&&o?(0,c.hj)(r,e.id,o):void 0,{targetUserIds:m,targetChatId:p}=l||{},g=m?m.map((e=>(0,c.dy)(r,e))).filter(Boolean):void 0,v=(0,i.zX)(e),y=v?(0,c.dy)(r,v):void 0;let b;if((0,i.Sm)(e,(0,c.dZ)(r),(0,c.NJ)(r)))if((0,i.Lo)(t)){const n=e&&((0,i.eA)(e)||t.senderId===t.chatId);b=(0,d.D)(f.i0,t,n?void 0:s,n?e:void 0,g,h,p,{asPlainText:!0})}else{const n=(0,i.zF)(f.i0,e.id,s),r=(0,i.MK)(f.i0,t,!1,60,!1);b=n?`${n}: ${r}`:r}else b="New message";return{title:(0,i.U)(f.i0,e,y),body:b}}(t,n,y);if(g()){var E;null!==(E=navigator.serviceWorker)&&void 0!==E&&E.controller&&navigator.serviceWorker.controller.postMessage({type:"showMessageNotification",payload:{title:w,body:C,icon:I,chatId:t.id,messageId:n.id,reaction:null==y?void 0:y.reaction}})}else{const e=(0,u.Sv)(),r={body:C,icon:I,badge:I,tag:String(n.id)};"vibrate"in navigator&&(r.vibrate=[200,100,200]);const o=new Notification(w,r);o.onclick=()=>{o.close(),e.focusMessage({chatId:t.id,messageId:n.id}),y&&e.startActiveReaction({messageId:n.id,reaction:y.reaction}),window.focus&&window.focus()},o.onshow=()=>{b(String(n.id)||t.id)}}}function M(e){var t;!a.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,{$:()=>a,L:()=>d});const r="kz_version",o=["Z","K"];function d(e){localStorage.setItem(r,JSON.stringify(e))}function a(){(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:()=>a,WZ:()=>s,g3:()=>u,un:()=>i});var r=n(782);const o="X",d="XXX XXX XXX XXX";function a(e,t){return e.filter((e=>e.iso2===t))}function u(e){var t;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",o=n.replace(/[^\d+]+/g,"");o.startsWith("+")&&(o=o.substr(1));const d=e.filter((e=>o.startsWith(e.countryCode))),a=(0,r.xH)(d.map((e=>(e.prefixes||[""]).map((t=>({code:`${e.countryCode}${t}`,country:e})))))),u=a.filter((e=>{let{code:t}=e;return o.startsWith(t)})).sort(((e,t)=>e.code.length-t.code.length));return null===(t=u[u.length-1])||void 0===t?void 0:t.country}function i(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),a=[];let u=0;for(let e=0;e{n.d(t,{V:()=>a,q:()=>d});var r=n(6137),o=n(6590);function d(e){const t="thread"!==e.type?`_${e.type}`:-1!==e.threadId?`_${e.threadId}`:"";return`${e.chatId}${t}`}function a(){if(!o.Oy)return;const[e,t]=o.Oy.replace(/^#/,"").split("_");if(null==e||!e.match(/^-?\d+$/))return;const n=["thread","pinned","scheduled"].includes(t);return{chatId:e,type:Boolean(t)&&n?t:"thread",threadId:Boolean(t)&&!n?Number(t):r._f}}},9118:(e,t,n)=>{function r(e,t){let n,r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],o=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return function(){for(var d=arguments.length,a=new Array(d),u=0;u{o&&e(...a),n=void 0}),t)}}function o(e,t){let n,r,o,d=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function(){r=!0;for(var a=arguments.length,u=new Array(a),i=0;i{if(!r)return self.clearInterval(n),void(n=void 0);r=!1,e(...o)}),t))}}function d(e){return i(v,e)}function a(e){return i(y,e)}function u(e){return i(b,e)}function i(e,t){let n,r=!1;return function(){for(var o=arguments.length,d=new Array(o),a=0;a{r=!1,t(...n)})))}}function s(e,t){self.requestIdleCallback?self.requestIdleCallback(e,{timeout:t}):b(e)}n.d(t,{$6:()=>u,D0:()=>y,Ds:()=>r,Gq:()=>w,P2:()=>o,Pn:()=>l,Q8:()=>s,R3:()=>b,T2:()=>v,mS:()=>d,wO:()=>c,wT:()=>a,zD:()=>I});const c=e=>new Promise((t=>{setTimeout((()=>t()),e)}));function l(){return new Promise((e=>{v(e)}))}let f,h,m,p,g;function v(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[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 y(e){v(e,!0)}function b(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[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 I(e){b(e,!0)}function w(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[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,{W:()=>d,Z:()=>o});try{r=/[^\p{L}\p{M}]+/iu}catch(e){r=/[^\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},3100:(e,t,n)=>{n.d(t,{f3:()=>m,jv:()=>l,ti:()=>s,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=(!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise((function(e){var t=function(){return indexedDB.databases().finally(e)};o=setInterval(t,100),t()})).finally((function(){return clearInterval(o)})):Promise.resolve()).then((()=>{const e=indexedDB.open("keyval-store");return e.onupgradeneeded=()=>e.result.createObjectStore(t),r(e)}));var o;return(e,r)=>n.then((n=>r(n.transaction(t,e).objectStore(t))))}(0,"keyval")),o}var a=n(3716),u=n(9524);const i=[1,2,3,4,5];function s(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(e&&localStorage.getItem(a.Vx))return!0;const t=localStorage.getItem(a.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(a.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(){[a.b_,"dc",...i.map((e=>`dc${e}_auth_key`)),...i.map((e=>`dc${e}_hash`))].forEach((e=>{localStorage.removeItem(e)}))}function f(){if(!s())return;const e=JSON.parse(localStorage.getItem(a.b_)),t=Number(e.dcID),n={},r={};return i.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){a.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(a.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){a.eM&&console.warn("Failed to load legacy session",e)}}async function m(){localStorage.removeItem(a.Vx);const e=await function(e=d()){return e("readonly",(e=>{if(e.getAllKeys)return r(e.getAllKeys());const t=[];return function(e,t){return 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([u.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)))])}},7370:(e,t,n)=>{n.d(t,{Z:()=>h});var r=n(9933),o=n(9118);const d=JSON.parse('{"--color-primary":["#3390EC","#8774E1"],"--color-primary-opacity":["#50A2E980","#8378DB80"],"--color-primary-shade":["#4a95d6","#7b71c6"],"--color-background":["#FFFFFF","#212121"],"--color-background-compact-menu":["#FFFFFFBB","#212121DD"],"--color-background-compact-menu-reactions":["#FFFFFFEB","#212121DD"],"--color-background-compact-menu-hover":["#00000011","#00000066"],"--color-background-secondary":["#f4f4f5","#0F0F0F"],"--color-background-secondary-accent":["#E4E4E5","#100f10"],"--color-background-own":["#EEFFDE","#766AC8"],"--color-background-own-apple":["#DCF8C5","#766AC8"],"--color-background-selected":["#F4F4F5","#2C2C2C"],"--color-background-own-selected":["#d0ffac","#6549d4"],"--color-chat-hover":["#F4F4F5","#2C2C2C"],"--color-chat-active":["#3390EC","#766AC8"],"--color-item-active":["#ededed","#292929"],"--color-text":["#000000","#FFFFFF"],"--color-text-secondary":["#707579","#AAAAAA"],"--color-icon-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","#8775DA"],"--color-reply-own-hover-apple":["#cbefb7","#8775DA"],"--color-reply-own-active":["#C5ECBE","#917DEA"],"--color-reply-own-active-apple":["#bae6a8","#917DEA"],"--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"],"--color-message-reaction":["#ebf3fd","#2b2a35"],"--color-message-reaction-hover":["#c5def9","#343147"],"--color-message-reaction-own":["#cef0ba","#675CAF"],"--color-message-reaction-hover-own":["#b5e0a4","#5B529B"]}');let a=!1;const u=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i,i=new Set(["--color-primary-shade","--color-text-secondary"]),s=(e,t,n)=>(1-n)*e+n*t,c=Object.keys(d).map((e=>({property:e,colors:[l(d[e][0]),l(d[e][1])]})));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){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;c.forEach((r=>{let{property:o,colors:d}=r;const a=Math.round(s(d[e].r,d[t].r,n)),u=Math.round(s(d[e].g,d[t].g,n)),c=Math.round(s(d[e].b,d[t].b,n)),l=void 0!==d[e].a?Math.round(s(d[e].a,d[t].a,n)):void 0;document.documentElement.style.setProperty(o,void 0!==l?`rgba(${a},${u},${c},${l/255})`:`rgb(${a},${u},${c})`),i.has(o)&&document.documentElement.style.setProperty(`${o}-rgb`,`${a},${u},${c}`)}))}const h=(e,t)=>{const n="dark"===e,d=a&&t,u=n?0:1,i=n?1:0,s=Date.now(),c=document.querySelector('meta[name="theme-color"]');document.documentElement.classList.remove("theme-"+(n?"light":"dark")),a&&document.documentElement.classList.add("no-animations"),document.documentElement.classList.add(`theme-${e}`),c&&c.setAttribute("content",n?"#212121":"#fff"),setTimeout((()=>{document.documentElement.classList.remove("no-animations")}),500),a=!0,d?(0,o.T2)((()=>{(0,r.cK)((()=>{const e=Math.min((Date.now()-s)/200,1);return f(u,i,function(e){return 1-(1-e)**3.5}(e)),e<1}))})):f(u,i)}},2155:(e,t,n)=>{n.d(t,{Xv:()=>i,bi:()=>u,kh:()=>d});var r=n(3681),o=n(4284);function d(e){return String(e).replace(/\d(?=(\d{3})+$)/g,"$& ")}function a(e){return".0"===String(e.toFixed(1)).substr(-2)?Math.round(e):e.toFixed(1).replace(".",",")}function u(e){return e<1e3?e:e<1e6?`${a(e/1e3)}K`:`${a(e/1e6)}M`}const i=(0,n(5155).Z)((function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]: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){return!e||!t||e.length<=t?e:`${e.substring(0,t)}...`}n.d(t,{Z:()=>r})},862:(e,t,n)=>{n.d(t,{Hu:()=>i,_y:()=>s,p6:()=>c});var r=n(7361),o=n(1394),d=n(9118);let a,u;const i="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";async function s(e,t){for(l();!u.wasmReady;)await(0,d.wO)(2e3);const{result:n,width:r,height:o}=await function(e,t){return new Promise((n=>{u.requests||(u.requests=new Map),u.requests.set(e,n),u.postMessage({id:e,blob:t})}))}(e,t);if(r&&o)return function(e){let{result:t,width:n,height:r}=e;return a||(a=document.createElement("canvas")),new Promise((e=>{const o=new ImageData(t,n,r);a.width=n,a.height=r,a.getContext("2d").putImageData(o,0,0),a.toBlob((t=>{e(null!=t?t: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 s(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(){u||(u=new Worker(new URL(n.p+n.u(536),n.b)),u.wasmReady=!1,u.onmessage=f)}function f(e){const{id:t}=e.data;switch(e.data.type){case"initialized":u.wasmReady=!0;break;case"result":if(u.requests.has(t)){const n=u.requests.get(t);u.requests.delete(t),n(e.data)}}}},1622:(e,t,n)=>{n.d(t,{IT:()=>l,W8:()=>h,px:()=>f});var r=n(3716),o=n(3555),d=n(3100);const a=["t.me","telegram.me"].map((e=>`//${e}/_websync_?`)),u=`${r.Ji} Z`,i="tgme_sync",s=()=>Math.floor(Number(new Date)/1e3);let c;const l=e=>{const t=s(),{canRedirect:n,ts:r}=JSON.parse(localStorage.getItem(i)||"{}");return n!==e||r+86400<=t?Promise.all(a.map((t=>new Promise(((n,r)=>{const o=document.createElement("script"),d=()=>Boolean(document.body.removeChild(o));o.src=t+new URLSearchParams({authed:Number(e).toString(),version:u}),document.body.appendChild(o),o.onload=()=>{(e=>{const t=s();localStorage.setItem(i,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=s(),{ts:t}=JSON.parse(localStorage.getItem(i)||"{}"),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))}function h(){localStorage.removeItem(i)}},3858:(e,t,n)=>{n.d(t,{Z:()=>h,z:()=>l});var r=n(9118),o=n(3716),d=n(7361);const a=d.wB&&f(),u=window.innerHeight;let i=l(),s=!1;const c=(0,r.P2)((()=>{i=l(),!s&&((i.width<=o.l3||i.width<=o.u_&&i.height<=o.rO)!==d.wB||d.wB&&a!==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:()=>i,getIsKeyboardVisible:()=>u>i.height,disableRefresh:function(){s=!0},enableRefresh:function(){s=!1}}},5155:(e,t,n)=>{n.d(t,{Z:()=>o});const r=new WeakMap;function o(e){return function(){let t=r.get(e);for(var n=arguments.length,o=new Array(n),d=0;d{e.exports=n.p+"app-inactive.bc7953c2dfebcabce2c4..png"},2162:(e,t,n)=>{e.exports=n.p+"monkey.a3d5fcdc50b18dc55695..svg"},5523:(e,t,n)=>{e.exports=n.p+"reaction-thumbs.f920d3f2147d986b6cbe..png"},4128:(e,t,n)=>{e.exports=n.p+"telegram-logo.1b2bb5b107f046ea9325..svg"}},u={};function i(e){var t=u[e];if(void 0!==t)return t.exports;var n=u[e]={exports:{}};return a[e].call(n.exports,n,n.exports,i),n.exports}i.m=a,i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,i.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);i.r(o);var d={};e=e||[null,t({}),t([]),t(t)];for(var a=2&r&&n;"object"==typeof a&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach((e=>d[e]=()=>n[e]));return d.default=()=>n,i.d(o,d),o},i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.f={},i.e=e=>Promise.all(Object.keys(i.f).reduce(((t,n)=>(i.f[n](e,t),t)),[])),i.u=e=>e+"."+{13:"1cb726dfb0fe77ff16db",99:"a19f6cfb125132c4ae9e",133:"e050778acd78ac17365a",161:"e3dd8735bd9f827bebc6",354:"a5e899b2a69f227670ec",395:"368d08862d9c65a1cf98",472:"38e2fa9338b8e031169b",501:"17afb8957510497ebb61",524:"f47aff24c24945077d39",536:"51c4121ec6034fff4884",616:"421a1d053cdd90ce3d23",654:"229871d7a07987919e6c",742:"b2feed9283c594eb9e2f",745:"7f9b9b63ef7b71c5b2d7",878:"ba2ac4194b79d543b70f",888:"3bcf93fb3c92294b2737",915:"7c6d5a7308348c57bbbd",941:"1399f916762c873a48a2",970:"81d005f8fdd6b7e03eb7",993:"c7c8681e7135da951723"}[e]+".js",i.miniCssF=e=>e+"."+{13:"1cb726dfb0fe77ff16db",133:"e050778acd78ac17365a",395:"368d08862d9c65a1cf98",472:"38e2fa9338b8e031169b",616:"421a1d053cdd90ce3d23",654:"229871d7a07987919e6c",878:"ba2ac4194b79d543b70f"}[e]+".css",i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n={},r="telegram-t:",i.l=(e,t,o,d)=>{if(n[e])n[e].push(t);else{var a,u;if(void 0!==o)for(var s=document.getElementsByTagName("script"),c=0;c{a.onerror=a.onload=null,clearTimeout(h);var o=n[e];if(delete n[e],a.parentNode&&a.parentNode.removeChild(a),o&&o.forEach((e=>e(r))),t)return t(r)},h=setTimeout(f.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=f.bind(null,a.onerror),a.onload=f.bind(null,a.onload),u&&document.head.appendChild(a)}},i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;i.g.importScripts&&(e=i.g.location+"");var t=i.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(/\/[^\/]+$/,"/"),i.p=e})(),o=e=>new Promise(((t,n)=>{var r=i.miniCssF(e),o=i.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 a=d&&("load"===d.type?"missing":d.type),u=d&&d.target&&d.target.href||t,i=new Error("Loading CSS chunk "+e+" failed.\n("+u+")");i.code="CSS_CHUNK_LOAD_FAILED",i.type=a,i.request=u,o.parentNode.removeChild(o),r(i)}},o.href=t,document.head.appendChild(o)})(e,o,t,n)})),d={179:0},i.f.miniCss=(e,t)=>{d[e]?t.push(d[e]):0!==d[e]&&{13:1,133:1,395:1,472:1,616:1,654:1,878:1}[e]&&t.push(d[e]=o(e).then((()=>{d[e]=0}),(t=>{throw delete d[e],t})))},(()=>{i.b=document.baseURI||self.location.href;var e={179:0};i.f.j=(t,n)=>{var r=i.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=i.p+i.u(t),a=new Error;i.l(d,(n=>{if(i.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;a.message="Loading chunk "+t+" failed.\n("+o+": "+d+")",a.name="ChunkLoadError",a.type=o,a.request=d,r[1](a)}}),"chunk-"+t,t)}};var t=(t,n)=>{var r,o,[d,a,u]=n,s=0;if(d.some((t=>0!==e[t]))){for(r in a)i.o(a,r)&&(i.m[r]=a[r]);u&&u(i)}for(t&&t(n);s{i(3592);var e=i(3716),t=i(3555),n=i(7361),r=i(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.Sv)(),a=o.payload;switch(o.type){case"focusMessage":d.focusMessage&&d.focusMessage(a),d.startActiveReaction&&a.reaction&&d.startActiveReaction({messageId:a.messageId,reaction:a.reaction});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{if(!navigator.serviceWorker.controller){const t=await navigator.serviceWorker.getRegistrations();t.length&&(e.eM&&console.log("[SW] Hard reload detected, re-enabling Service Worker"),await Promise.all(t.map((e=>e.unregister()))))}await navigator.serviceWorker.register(new URL(i.p+i.u(524),i.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.Sv)().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 a=i(4050),u=i(2916);const s={isLeftColumnShown:!0,isChatInfoShown:!1,newChatMembersProgress:i(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:{volume:e.Qx,playbackRate:e.mw,isMuted:!1},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,isConnectionStatusMinimized:!0},themes:{light:{isBlurred:!0,patternColor:e.g},dark:{isBlurred:!0,patternColor:e.Vv}},privacy:{},notifyExceptions:{}},twoFaSettings:{},activeReactions:{},shouldShowContextMenuHint:!0,activeDownloads:{byChatId:{}},serviceNotifications:[],statistics:{byChatId:{}}};var c=i(5116),l=i(6137),f=i(9118),h=i(8674),m=i(782),p=i(1192),g=i(3100),v=i(5780),y=i(5806),b=i(6974);const I=(0,f.P2)((()=>(0,f.Q8)(P)),5e3,!1);let w,C=!1;function S(){C=!0,w=(0,f.Gq)(P,!0),window.addEventListener("blur",P),(0,c.ll)(I)}function E(){C=!1,(0,c.Iq)(I),window.removeEventListener("blur",P),w&&w()}function P(){if(!C||(0,h.zG)())return;const n=(0,t.Rd)();if(n.isLoggingOut)return;const r={...s,...(0,m.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},mediaViewer:{volume:n.mediaViewer.volume,playbackRate:n.mediaViewer.playbackRate,isMuted:n.mediaViewer.isMuted},isChatInfoShown:M(n),users:A(n),chats:k(n),messages:T(n),globalSearch:{recentlyFoundChatIds:n.globalSearch.recentlyFoundChatIds},settings:N(n),chatFolders:L(n),groupCalls:R(n),availableReactions:x(n)},o=JSON.stringify(r);localStorage.setItem(e.Uh,o)}function M(t){return window.innerWidth>e._m&&t.isChatInfoShown}function A(t){var n,r,o,d,a;const{users:{byId:u,statusesById:i},currentUserId:s}=t,{chatId:c}=(0,p.Bt)(t)||{},l=null===(n=(0,p.P2)(t))||void 0===n?void 0:n.map((e=>{let{id:t}=e;return t})),f=(0,m.Tw)([...s?[s]:[],...c&&(0,y.YC)(c)?[c]:[],...l||[],...t.topPeers.userIds||[],...(null===(r=(0,b.gO)(e.Nf))||void 0===r?void 0:r.filter(y.YC))||[],...(null===(o=(0,b.gO)(e.WS))||void 0===o?void 0:o.filter(y.YC))||[],...(null===(d=t.contactList)||void 0===d?void 0:d.userIds)||[],...(null===(a=t.globalSearch.recentlyFoundChatIds)||void 0===a?void 0:a.filter(y.YC))||[],...Object.keys(u)]).slice(0,e.lO);return{byId:(0,m.ei)(u,f),statusesById:(0,m.ei)(i,f)}}function k(t){const{chats:{byId:n},currentUserId:r}=t,o=(0,p.jr)(t),d=(0,m.Tw)([...r?[r]:[],...o?[o.id]:[],...(0,b.gO)(e.Nf)||[],...(0,b.gO)(e.WS)||[],...t.globalSearch.recentlyFoundChatIds||[],...Object.keys(n)]).slice(0,e.gJ);return{...t.chats,isFullyLoaded:{},byId:(0,m.ei)(t.chats.byId,d)}}function T(t){var n;const{currentUserId:r}=t,o={},{chatId:d}=(0,p.Bt)(t)||{};return[...d?[d]:[],...r?[r]:[],...(null===(n=(0,b.gO)(e.Nf))||void 0===n?void 0:n.slice(0,e.Rk))||[]].forEach((e=>{const n=t.messages.byChatId[e];if(!n)return;const r=n.threadsById[l._f];r&&r.viewportIds&&(o[e]={byId:(0,m.ei)(n.byId,r.viewportIds),threadsById:{[l._f]:r}})})),{byChatId:o,messageLists:[],sponsoredByChatId:{}}}function N(e){const{byKey:t,themes:n}=e.settings;return{byKey:t,themes:n,privacy:{},notifyExceptions:{}}}function L(e){return{...e.chatFolders,activeChatFolder:0}}function R(e){return{...e.groupCalls,byId:{},activeGroupCallId:void 0,isGroupCallPanelHidden:void 0,isFallbackConfirmOpen:void 0}}function x(e){var t;return null===(t=e.availableReactions)||void 0===t?void 0:t.map((e=>(0,m.ei)(e,["reaction","staticIcon","title","isInactive"])))}e.sd||((0,t.iw)("saveSession",(()=>{C||S()})),(0,t.iw)("reset",(()=>{localStorage.removeItem(e.Uh),C&&E()}))),(0,t.iw)("init",(()=>{const t=(0,m.Xh)(s);return function(t){if(!e.sd)return(0,g.ti)(!0)?(S(),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:a,...u}=t.settings.byKey;t.settings.byKey={...u,canAutoLoadPhotoFromContacts:e,canAutoLoadVideoFromContacts:e,canAutoLoadPhotoInPrivateChats:n,canAutoLoadVideoInPrivateChats:n,canAutoLoadPhotoInGroups:r,canAutoLoadVideoInGroups:r,canAutoLoadPhotoInChannels:o,canAutoLoadVideoInChannels:o,canAutoPlayVideos:d,canAutoPlayGifs:a}}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),void 0===t.mediaViewer.volume&&(t.mediaViewer.volume=e.Qx),void 0===t.mediaViewer.playbackRate&&(t.mediaViewer.playbackRate=e.mw),t.groupCalls||(t.groupCalls=n.groupCalls),t.users.statusesById||(t.users.statusesById={}),t.messages.sponsoredByChatId||(t.messages.sponsoredByChatId={}),t.activeReactions||(t.activeReactions={})}(o,t);const d={...t,...o},a=n.wB?void 0:(0,v.V)();return{...d,messages:{...d.messages,messageLists:a?[a]:[]}}}(t)):void E()}(t)||t}));var B=i(3858);const F="tt-active-tab",O=String(Date.now()+Math.random());let D;localStorage.setItem(F,O);const Z=window.setInterval((()=>{D&&localStorage.getItem(F)!==O&&(D(),clearInterval(Z))}),2e3);var _=i(706),$=(i(9005),i(3456),i(5456),i(1371),i(8304),i(6590)),U=i(2825),j=i(1212),V=i(1394);const W=["400 1em Roboto","500 1em Roboto"];function G(){if("fonts"in document)return Promise.all(W.map((e=>document.fonts.load(e))))}var H=i(647),z=i(9203),K=i(6752),J=i(4128),q=i(5523),Y=i(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,U.RT)(t);return r?H.he(r,l.IU.BlobUrl):void 0})))}const X={main:()=>Promise.all([(0,z.$y)(z.gl.Main,"Main").then(G),Q(),(0,V.pt)(q)]),authPhoneNumber:()=>Promise.all([G(),(0,V.pt)(J)]),authCode:()=>(0,V.pt)(Y),authPassword:()=>(0,V.pt)(Y),authQrCode:G},ee=(0,t.c$)((e=>{const t=(0,p.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,p.Jf)(e),leftColumnWidth:e.leftColumnWidth}}))((e=>{let{page:n,children:r,hasCustomBackground:o,hasCustomBackgroundColor:d,isRightColumnShown:u,shouldSkipHistoryAnimations:i,leftColumnWidth:s}=e;const{setIsUiReady:c}=(0,t.Sv)(),[l,h]=(0,_.Z)(),{shouldRender:m,transitionClassNames:p}=(0,j.Z)(!l,void 0,!0);return(0,a.d4)((()=>{let e;return Promise.race([(0,f.wO)(700),(async()=>{try{await X[n]()}catch(e){}})()]).then((()=>{h(),c({uiReadyState:1}),e=window.setTimeout((()=>{c({uiReadyState:2})}),1e3)})),()=>{e&&(clearTimeout(e),e=void 0),c({uiReadyState:0})}}),[]),a.ZP.createElement("div",{id:"UiLoader"},r,m&&!i&&a.ZP.createElement("div",{className:(0,K.Z)("mask",p)},"main"===n?a.ZP.createElement(a.ZP.Fragment,null,a.ZP.createElement("div",{className:"left",style:s?`width: ${s}px`:void 0}),a.ZP.createElement("div",{className:(0,K.Z)("middle",o&&"custom-bg-image",d&&"custom-bg-color",u&&"with-right-column")}),u&&a.ZP.createElement("div",{className:"right"})):a.ZP.createElement("div",{className:"blank"})))}));var te=i(6272),ne=i(711),re=i(9107);const oe=(e,t)=>{const[n,r]=(0,a.eJ)();return e&&ne.Pn(e,t).then(r),n};function de(){let e=navigator.language;return e&&"pt-br"!==e&&(e=e.substr(0,2)),e}var ae=i(231),ue=i(4605),ie=i(7687),se=i(4288),ce=i(5765),le=i(2340),fe=i(4284),he=i(9290),me=i(3106),pe=i(8964),ge=i(9204);const ve=200+e.fK,ye=(0,a.X$)((0,t.c$)((e=>{const{countryList:{phoneCodes:t}}=e;return{phoneCodeList:t}}))((e=>{let{id:t,value:n,isLoading:r,onChange:o,phoneCodeList:d}=e;const u=(0,re.Z)(),i=(0,a.sO)(null),[s,c]=(0,a.eJ)(),[l,f]=(0,a.eJ)([]),h=(0,a.I4)((e=>{c(e),f(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(!t.length)return e;const n=(0,ce.W)(t);return e.filter((e=>n(e.defaultName)||e.name&&n(e.name)))}(d,e))}),[d]);(0,he.Z)((e=>{let[t]=e;0===(null==t?void 0:t.length)&&d.length>0&&h(s)}),[d,h]);const m=(0,a.I4)((e=>{o(e),setTimeout((()=>h(void 0)),ve)}),[o,h]),p=(0,a.I4)((e=>{h(e.currentTarget.value)}),[h]),g=(0,a.I4)((e=>{if(8!==e.keyCode)return;const t=e.currentTarget;n&&void 0===s&&(t.value=""),h(t.value)}),[s,h,n]),v=(0,a.I4)((e=>{let{onTrigger:o,isOpen:d}=e;const c=()=>{if(d)return;setTimeout((()=>{i.current.select()}),50),o();const e=document.getElementById("auth-phone-number-form");e.scrollTo({top:e.scrollHeight,behavior:"smooth"})},l=null!=s?s:(null==n?void 0:n.name)||(null==n?void 0:n.defaultName)||"";return a.ZP.createElement("div",{className:(0,K.Z)("input-group",n&&"touched")},a.ZP.createElement("input",{ref:i,className:(0,K.Z)("form-control",d&&"focus"),type:"text",id:t,value:l,autoComplete:"off",onClick:c,onFocus:c,onInput:e=>{p(e),c()},onKeyDown:g}),a.ZP.createElement("label",null,u("Login.SelectCountry.Title")),r?a.ZP.createElement(ge.Z,{color:"black"}):a.ZP.createElement("i",{onClick:c,className:(0,K.Z)("css-icon-down",d&&"open")}))}),[s,p,g,t,r,u,n]);return a.ZP.createElement(me.Z,{className:"CountryCodeInput",trigger:v},l.map((e=>a.ZP.createElement(pe.Z,{key:`${e.iso2}-${e.countryCode}`,className:n&&e.iso2===n.iso2?"selected":"",onClick:()=>m(e)},a.ZP.createElement("span",{className:"country-flag"},(0,le.Z)((0,fe.Wg)(e.iso2),["hq_emoji"])),a.ZP.createElement("span",{className:"country-name"},e.name||e.defaultName),a.ZP.createElement("span",{className:"country-code"},"+",e.countryCode)))),!l.length&&a.ZP.createElement(pe.Z,{key:"no-results",className:"no-results",disabled:!0},a.ZP.createElement("span",null,u("lng_country_none"))))})));let be=!1;const Ie=(0,a.X$)((0,t.c$)((e=>{const{settings:{byKey:{language:t}},countryList:{phoneCodes:n}}=e;return{...(0,m.ei)(e,["connectionState","authState","authPhoneNumber","authIsLoading","authIsLoadingQrCode","authError","authRememberMe","authNearestCountry"]),language:t,phoneCodeList:n}}))((e=>{let{connectionState:r,authState:o,authPhoneNumber:d,authIsLoading:u,authIsLoadingQrCode:i,authError:s,authRememberMe:c,authNearestCountry:l,phoneCodeList:f,language:h}=e;const{setAuthPhoneNumber:m,setAuthRememberMe:p,loadNearestCountry:g,loadCountryList:v,clearAuthError:y,goToAuthQrCode:b,setSettingOption:I}=(0,t.Sv)(),w=(0,re.Z)(),C=(0,a.sO)(null),S=de(),E=oe(S,"ContinueOnThisLanguage"),[P,M]=(0,a.eJ)(),[A,k]=(0,a.eJ)(),[T,N]=(0,a.eJ)(!1),[L,R]=(0,a.eJ)(),[x,B,F]=(0,_.Z)(),O=P?`+${P.countryCode} ${A||""}`:A,D=O&&O.replace(/[^\d]+/g,"").length>=7;(0,a.d4)((()=>{n.$b||C.current.focus()}),[P]),(0,a.d4)((()=>{"connectionStateReady"!==r||l||g()}),[r,l,g]),(0,a.d4)((()=>{"connectionStateReady"===r&&v({langCode:h})}),[r,h,v]),(0,a.d4)((()=>{l&&f&&!P&&!T&&M((0,te.U9)(f,l)[0])}),[P,l,T,f]);const Z=(0,a.I4)((e=>{e.length||k("");const t=f&&(0,te.g3)(f,e),n=!P||t&&t.iso2!==P.iso2||!t&&e.length?t:P;(!P||!n||n&&n.iso2!==P.iso2)&&M(n),k((0,te.un)(e,n))}),[f,P]),$=(0,a.I4)((()=>{B(),(0,ne.m0)(S,(()=>{F(),I({language:S})}))}),[B,I,S,F]);(0,a.d4)((()=>{void 0===A&&d&&Z(d)}),[d,A,Z]),(0,a.bt)((()=>{C.current&&L&&C.current.setSelectionRange(...L)}),[L]);const U=(0,a.sO)(!1),j=(0,a.I4)((()=>{U.current=!0,requestAnimationFrame((()=>{U.current=!1}))}),[]),W=(0,a.I4)((e=>{M(e),k("")}),[]),H=(0,a.I4)((e=>{s&&y(),be||(be=!0,G(),(0,V.pt)(Y));const{value:t,selectionStart:r,selectionEnd:o}=e.target;R(r&&o&&o1&&!U.current;Z(d?`${P.countryCode} ${t}`:t)}),[s,y,P,O,Z]),z=(0,a.I4)((e=>{p(e.target.checked)}),[p]),K="authorizationStateWaitPhoneNumber"===o;return a.ZP.createElement("div",{id:"auth-phone-number-form",className:"custom-scroll"},a.ZP.createElement("div",{className:"auth-form"},a.ZP.createElement("div",{id:"logo"}),a.ZP.createElement("h2",null,"Telegram"),a.ZP.createElement("p",{className:"note"},w("StartText")),a.ZP.createElement("form",{action:"",onSubmit:function(e){e.preventDefault(),u||D&&m({phoneNumber:O})}},a.ZP.createElement(ye,{id:"sign-in-phone-code",value:P,isLoading:!l&&!P,onChange:W}),a.ZP.createElement(ie.Z,{ref:C,id:"sign-in-phone-number",label:w("Login.PhonePlaceholder"),value:O,error:s&&w(s),inputMode:"tel",onChange:H,onPaste:n.s$?j:void 0}),a.ZP.createElement(ue.Z,{id:"sign-in-keep-session",label:"Keep me signed in",checked:Boolean(c),onChange:z}),D&&(K?a.ZP.createElement(ae.Z,{type:"submit",ripple:!0,isLoading:u},w("Login.Next")):a.ZP.createElement(se.Z,null)),K&&a.ZP.createElement(ae.Z,{isText:!0,ripple:!0,isLoading:i,onClick:b},w("Login.QR.Login")),S&&S!==h&&E&&a.ZP.createElement(ae.Z,{isText:!0,isLoading:x,onClick:$},E))))})));var we=i(8778);const Ce=(0,a.X$)((()=>{const e=(0,we.Z)(z.gl.Auth,"AuthCode");return e?a.ZP.createElement(e,null):a.ZP.createElement(se.Z,null)})),Se=(0,a.X$)((()=>{const e=(0,we.Z)(z.gl.Auth,"AuthPassword");return e?a.ZP.createElement(e,null):a.ZP.createElement(se.Z,null)})),Ee=(0,a.X$)((()=>{const e=(0,we.Z)(z.gl.Auth,"AuthRegister");return e?a.ZP.createElement(e,null):a.ZP.createElement(se.Z,null)}));let Pe=null;class Me{}Me.render=function(e,t){Pe(e,t)},self.QrCreator=Me,function(e){function t(t,n,r,o){var d={},a=e(r,n);a.u(t),a.J(),o=o||0;var u=a.h(),i=a.h()+2*o;return d.text=t,d.level=n,d.version=r,d.O=i,d.a=function(e,t){return t-=o,!(0>(e-=o)||e>=u||0>t||t>=u)&&a.a(e,t)},d}function n(e,t,n,r,o,d,a,u,i,s){function c(t,n,r,o,a,u,i){t?(e.lineTo(n+u,r+i),e.arcTo(n,r,o,a,d)):e.lineTo(n,r)}a?e.moveTo(t+d,n):e.moveTo(t,n),c(u,r,n,r,o,-d,0),c(i,r,o,t,o,0,-d),c(s,t,o,t,n,d,0),c(a,t,n,r,n,0,d)}function r(e,t,n,r,o,d,a,u,i,s){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)}a&&c(t,n,d,d),u&&c(r,n,-d,d),i&&c(r,o,-d,-d),s&&c(t,o,d,-d)}function o(e,o){e:{var d=o.text,a=o.v,u=o.N,i=o.K,s=o.P;for(u=Math.max(1,u||1),i=Math.min(40,i||40);u<=i;u+=1)try{var c=t(d,a,u,s);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)),a=c.O,i=o.size/a,d.beginPath(),s=0;sMath.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};Pe=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,a){function u(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 i(e,n){for(var a=l=4*o+17,i=Array(a),m=0;m=v;v+=1)for(var y=-2;2>=y;y+=1)c[p+v][g+y]=-2==v||2==v||-2==y||2==y||0==v&&0==y}for(a=8;ai;i+=1)m=!e&&1==(a>>i&1),c[6>i?i:8>i?i+1:l-15+i][8]=m,c[8][8>i?l-i-1:9>i?15-i:14-i]=m;if(c[l-8][8]=!e,7<=o){for(a=r.A(o),i=0;18>i;i+=1)m=!e&&1==(a>>i&1),c[Math.floor(i/3)][i%3+l-8-3]=m;for(i=0;18>i;i+=1)m=!e&&1==(a>>i&1),c[i%3+l-8-3][Math.floor(i/3)]=m}if(null==f){for(e=d.I(o,s),a=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}(),i=0;i8*m)throw Error("code length overflow. ("+a.f()+">"+8*m+")");for(a.f()+4<=8*m&&a.put(0,4);0!=a.f()%8;)a.m(!1);for(;!(a.f()>=8*m||(a.put(236,8),a.f()>=8*m));)a.put(17,8);var b=0;for(m=i=0,p=Array(e.length),g=Array(e.length),v=0;vv;v+=1)null==c[i][g-v]&&(y=!1,p>>m&1)),n(i,g-v)&&(y=!y),c[i][g-v]=y,-1==--m&&(p+=1,m=7));if(0>(i+=a)||l<=i){i-=a,a=-a;break}}}var s=n[a],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){i(!0,n);var o=r.D(m);(0==n||e>o)&&(e=o,t=n)}i(!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()),a=0;ar?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]],r={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=u;u+=1)if(!(0>r+u||t<=r+u))for(var i=-1;1>=i;i+=1)0>o+i||t<=o+i||(0!=u||0!=i)&&a==e.a(r+u,o+i)&&(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]],r={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}}))((n=>{let{connectionState:r,authState:o,authQrCode:d,language:u}=n;const{returnToAuthPhoneNumber:i,setSettingOption:s}=(0,t.Sv)(),c=de(),l=(0,re.Z)(),f=(0,a.sO)(null),h=oe(c,"ContinueOnThisLanguage"),[m,p,g]=(0,_.Z)();(0,a.d4)((()=>{if(!d||"connectionStateReady"!==r)return;const e=f.current;e.innerHTML="",e.classList.remove("pre-animate"),Ae.render({text:`tg://login?token=${d.token}`,radius:.5,ecLevel:"M",fill:"#4E96D4",size:280},e)}),[r,d]),(0,a.d4)((()=>{"connectionStateReady"===r&&(0,ne.m0)(e.sR)}),[r]);const v=(0,a.I4)((()=>{p(),(0,ne.m0)(c,(()=>{g(),s({language:c})}))}),[p,s,c,g]),y="authorizationStateWaitQrCode"===o;return a.ZP.createElement("div",{id:"auth-qr-form",className:"custom-scroll"},a.ZP.createElement("div",{className:"auth-form qr"},d?a.ZP.createElement("div",{key:"qr-container",className:"qr-container pre-animate",ref:f}):a.ZP.createElement("div",{key:"qr-loading",className:"qr-loading"},a.ZP.createElement(se.Z,null)),a.ZP.createElement("h3",null,l("Login.QR.Title")),a.ZP.createElement("ol",null,a.ZP.createElement("li",null,a.ZP.createElement("span",null,l("Login.QR.Help1"))),a.ZP.createElement("li",null,a.ZP.createElement("span",null,(0,le.Z)(l("Login.QR2.Help2"),["simple_markdown"]))),a.ZP.createElement("li",null,a.ZP.createElement("span",null,l("Login.QR.Help3")))),y&&a.ZP.createElement(ae.Z,{isText:!0,onClick:i},l("Login.QR.Cancel")),c&&c!==u&&h&&a.ZP.createElement(ae.Z,{isText:!0,isLoading:m,onClick:v},h)))}))),Te=(0,a.X$)((0,t.c$)((e=>(0,m.ei)(e,["authState"])))((e=>{let{authState:r}=e;const{reset:o,initApi:d,returnToAuthPhoneNumber:u,goToAuthQrCode:i}=(0,t.Sv)();(0,a.d4)((()=>{o(),d()}),[o,d]);const s="iOS"===n.Lt||"Android"===n.Lt;switch((0,$.ZP)(!s&&"authorizationStateWaitPhoneNumber"===r||s&&"authorizationStateWaitQrCode"===r,(()=>{s?u():i()})),(0,a.d4)((()=>(B.Z.disableRefresh(),()=>{B.Z.enableRefresh()})),[]),r){case"authorizationStateWaitCode":return a.ZP.createElement(ee,{page:"authCode",key:"authCode"},a.ZP.createElement(Ce,null));case"authorizationStateWaitPassword":return a.ZP.createElement(ee,{page:"authPassword",key:"authPassword"},a.ZP.createElement(Se,null));case"authorizationStateWaitRegistration":return a.ZP.createElement(Ee,null);case"authorizationStateWaitPhoneNumber":return a.ZP.createElement(ee,{page:"authPhoneNumber",key:"authPhoneNumber"},a.ZP.createElement(Ie,null));case"authorizationStateWaitQrCode":return a.ZP.createElement(ee,{page:"authQrCode",key:"authQrCode"},a.ZP.createElement(ke,null));default:return s?a.ZP.createElement(ee,{page:"authPhoneNumber",key:"authPhoneNumber"},a.ZP.createElement(Ie,null)):a.ZP.createElement(ee,{page:"authQrCode",key:"authQrCode"},a.ZP.createElement(ke,null))}}))),Ne=(0,a.X$)((()=>{const e=(0,we.Z)(z.gl.Main,"Main");return e?a.ZP.createElement(e,null):void 0}));var Le=i(5359);const Re=()=>a.ZP.createElement("div",{id:"AppInactive"},a.ZP.createElement("div",{className:"content"},a.ZP.createElement("img",{src:Le,alt:""}),a.ZP.createElement("h3",{className:"title"},"Such error, many tabs"),a.ZP.createElement("div",{className:"description"},"Telegram supports only one active tab with the app.",a.ZP.createElement("br",null),"Please reload this page to continue using this tab or close it."),a.ZP.createElement("div",{className:"actions"},a.ZP.createElement(ae.Z,{isText:!0,ripple:!0,onClick:()=>{window.location.reload()}},"Reload app"))));function xe(){return a.ZP.createElement(ee,{page:"main",key:"main"},a.ZP.createElement(Ne,null))}const Be=(0,t.c$)((e=>(0,m.ei)(e,["authState"])))((n=>{let{authState:r}=n;const{disconnect:o}=(0,t.Sv)(),[d,u]=(0,_.Z)(!1);if((0,a.d4)((()=>{(0,B.z)(),D=()=>{o(),document.title=`${e.Ti}${e.ou}`,u()}}),[o,u]),d)return a.ZP.createElement(Re,null);if(r)switch(r){case"authorizationStateWaitPhoneNumber":case"authorizationStateWaitCode":case"authorizationStateWaitPassword":case"authorizationStateWaitRegistration":case"authorizationStateWaitQrCode":return a.ZP.createElement(Te,null);case"authorizationStateClosed":case"authorizationStateClosing":case"authorizationStateLoggingOut":case"authorizationStateReady":return xe()}return(0,g.ti)(!0)?xe():a.ZP.createElement(Te,null)}));e.eM&&console.log(">>> INIT"),(0,t.Sv)().init(),e.eM&&console.log(">>> START INITIAL RENDER"),u.Z.render(a.ZP.createElement(Be,null),document.getElementById("root")),e.eM&&console.log(">>> FINISH INITIAL RENDER"),document.addEventListener("dblclick",(()=>{console.warn("GLOBAL STATE",(0,t.Rd)())}))})()})(); +//# sourceMappingURL=main.040a86fe9347e4854db9.js.map \ No newline at end of file diff --git a/dist/main.687698a9e9aa68d75d14.js.map b/dist/main.040a86fe9347e4854db9.js.map similarity index 99% rename from dist/main.687698a9e9aa68d75d14.js.map rename to dist/main.040a86fe9347e4854db9.js.map index fac06866..03d7de66 100644 --- a/dist/main.687698a9e9aa68d75d14.js.map +++ b/dist/main.040a86fe9347e4854db9.js.map @@ -1 +1 @@ -{"version":3,"file":"main.687698a9e9aa68d75d14.js","mappings":"uBACIA,EADAC,ECAAC,EACAC,ECwCAC,EASAC,E,wFC/BJ,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,mBAsEhC,SAA2BN,GACzBL,EAAOY,iBAAiB,WAAW,IAAkC,IAAjC,KAAEC,GAA+B,EACnE,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,mBAAd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AC,GAAD,SC1C7C1+F,EAAAA,IAEFC,QAAQC,IAAI,aAGduH,EAAAA,EAAAA,MAAaihB,OAET1oB,EAAAA,IAEFC,QAAQC,IAAI,4BAGd2+F,EAAAA,EAAAA,OACE,mBAAC,GAAD,MACA11F,SAAS+uF,eAAe,SAGtBl4F,EAAAA,IAEFC,QAAQC,IAAI,6BAGdiJ,SAAS9I,iBAAiB,YAAY,KAEpCJ,QAAQ4B,KAAK,gBAAgBgnB,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/renderMessageText.ts","webpack://telegram-t/./src/components/common/helpers/renderText.tsx","webpack://telegram-t/./src/components/common/spoiler/Spoiler.tsx","webpack://telegram-t/./src/components/common/helpers/renderTextWithEntities.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/global/actions/api/initial.ts","webpack://telegram-t/./src/global/actions/api/settings.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/initial.ts","webpack://telegram-t/./src/global/actions/ui/initial.ts","webpack://telegram-t/./src/global/actions/ui/settings.ts","webpack://telegram-t/./src/global/helpers/chats.ts","webpack://telegram-t/./src/global/helpers/messages.ts","webpack://telegram-t/./src/global/helpers/reactions.ts","webpack://telegram-t/./src/global/helpers/messageSummary.ts","webpack://telegram-t/./src/global/helpers/messageMedia.ts","webpack://telegram-t/./src/global/helpers/localSearch.ts","webpack://telegram-t/./src/global/helpers/payments.ts","webpack://telegram-t/./src/global/helpers/users.ts","webpack://telegram-t/./src/global/index.ts","webpack://telegram-t/./src/global/reducers/chats.ts","webpack://telegram-t/./src/global/reducers/symbols.ts","webpack://telegram-t/./src/global/reducers/users.ts","webpack://telegram-t/./src/global/reducers/globalSearch.ts","webpack://telegram-t/./src/global/reducers/localSearch.ts","webpack://telegram-t/./src/global/reducers/management.ts","webpack://telegram-t/./src/global/reducers/settings.ts","webpack://telegram-t/./src/global/reducers/twoFaSettings.ts","webpack://telegram-t/./src/global/reducers/payments.ts","webpack://telegram-t/./src/global/reducers/statistics.ts","webpack://telegram-t/./src/global/reducers/messages.ts","webpack://telegram-t/./src/global/selectors/chats.ts","webpack://telegram-t/./src/global/selectors/symbols.ts","webpack://telegram-t/./src/global/selectors/messages.ts","webpack://telegram-t/./src/global/selectors/localSearch.ts","webpack://telegram-t/./src/global/selectors/statistics.ts","webpack://telegram-t/./src/global/selectors/management.ts","webpack://telegram-t/./src/global/selectors/ui.ts","webpack://telegram-t/./src/global/selectors/globalSearch.ts","webpack://telegram-t/./src/global/selectors/payments.ts","webpack://telegram-t/./src/global/selectors/settings.ts","webpack://telegram-t/./src/global/selectors/users.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/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/callbacks.ts","webpack://telegram-t/./src/util/captureEscKeyListener.ts","webpack://telegram-t/./src/util/captureKeyboardListeners.ts","webpack://telegram-t/./src/util/clipboard.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/folderManager.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/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/index.js","webpack://telegram-t/./node_modules/safari-14-idb-fix/dist/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/./src/util/withCache.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/initialState.ts","webpack://telegram-t/./src/global/cache.ts","webpack://telegram-t/./src/global/init.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 = {\"13\":1,\"133\":1,\"395\":1,\"472\":1,\"616\":1,\"654\":1,\"878\":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 { Api } from '../../../lib/gramjs';\nimport { ApiInitialArgs, ApiOnProgress, OnApiUpdate } from '../../types';\nimport { Methods, MethodArgs, MethodResponse } from '../methods/types';\nimport { WorkerMessageEvent, 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 const promise = makeRequest({\n type: 'callMethod',\n name: fnName,\n args,\n });\n\n // Some TypeScript magic to make sure `VirtualClass` is never returned from any method\n if (DEBUG) {\n (async () => {\n try {\n type ForbiddenTypes =\n Api.VirtualClass\n | (Api.VirtualClass | undefined)[];\n type ForbiddenResponses =\n ForbiddenTypes\n | (AnyLiteral & { [k: string]: ForbiddenTypes });\n\n // Unwrap all chained promises\n const response = await promise;\n // Make sure responses do not include `VirtualClass` instances\n const allowedResponse: Exclude = response;\n // Suppress \"unused variable\" constraint\n void allowedResponse;\n } catch (err) {\n // Do noting\n }\n })();\n }\n\n return promise 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\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', () => {\n void ensureWorkerPing();\n // Sometimes a single check is not enough\n setTimeout(() => ensureWorkerPing(), 1000);\n });\n}\n\nasync function ensureWorkerPing() {\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","// 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 | ArrayBuffer;\nexport type ApiPreparedMedia = 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 isLottie: boolean;\n isVideo: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isLottie?: true;\n isVideos?: 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\ninterface ApiGeoPoint {\n long: number;\n lat: number;\n accessHash: string;\n accuracyRadius?: number;\n}\n\ninterface ApiGeo {\n type: 'geo';\n geo: ApiGeoPoint;\n}\n\ninterface ApiVenue {\n type: 'venue';\n geo: ApiGeoPoint;\n title: string;\n address: string;\n provider: string;\n venueId: string;\n venueType: string;\n}\n\ninterface ApiGeoLive {\n type: 'geoLive';\n geo: ApiGeoPoint;\n heading?: number;\n period: number;\n}\n\nexport type ApiLocation = ApiGeo | ApiVenue | ApiGeoLive;\n\nexport type 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 Spoiler = 'MessageEntitySpoiler',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: string;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n location?: ApiLocation;\n };\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 reactors?: {\n nextOffset?: string;\n count: number;\n reactions: ApiUserReaction[];\n };\n reactions?: ApiReactions;\n}\n\nexport interface ApiReactions {\n canSeeList?: boolean;\n results: ApiReactionCount[];\n recentReactions?: ApiUserReaction[];\n}\n\nexport interface ApiUserReaction {\n userId: string;\n reaction: string;\n}\n\nexport interface ApiReactionCount {\n isChosen?: boolean;\n count: number;\n reaction: string;\n}\n\nexport interface ApiAvailableReaction {\n selectAnimation?: ApiDocument;\n staticIcon?: ApiDocument;\n centerIcon?: ApiDocument;\n aroundAnimation?: ApiDocument;\n reaction: string;\n title: string;\n isInactive?: 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' | 'illegalDrugs' | 'personalDetails' | '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 { getActions } from '../../global';\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?: React.ReactNode;\n isRtl?: boolean;\n};\n\nconst SafeLink: FC = ({\n url,\n text,\n className,\n children,\n isRtl,\n}) => {\n const { toggleSafeLinkModal, openTelegramLink } = getActions();\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","import 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\nconst parseEmojiOnlyString = (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\nexport default parseEmojiOnlyString;\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 { getActions } from '../../global';\n\ntype OwnProps = {\n className?: string;\n sender?: ApiUser | ApiChat;\n children: React.ReactNode;\n};\n\nconst UserLink: FC = ({\n className, sender, children,\n}) => {\n const { openChat } = getActions();\n\n const handleClick = useCallback(() => {\n if (sender) {\n openChat({ id: sender.id });\n }\n }, [sender, openChat]);\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 { getActions } from '../../global';\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: React.ReactNode;\n};\n\nconst MessageLink: FC = ({\n className, message, children,\n}) => {\n const { focusMessage } = getActions();\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 { getActions } from '../../global';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n chatId?: string;\n children: React.ReactNode;\n};\n\nconst ChatLink: FC = ({\n className, chatId, children,\n}) => {\n const { openChat } = getActions();\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 { getActions } from '../../global';\n\ntype OwnProps = {\n className?: string;\n groupCall?: Partial;\n children: React.ReactNode;\n};\n\nconst GroupCallLink: FC = ({\n className, groupCall, children,\n}) => {\n const { joinGroupCall } = getActions();\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 getMessageSummaryText,\n getUserFullName,\n} from '../../../global/helpers';\nimport trimText from '../../../util/trimText';\nimport { formatCurrency } from '../../../util/formatCurrency';\nimport { TextPart, renderMessageSummary } 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 RenderOptions {\n asPlainText?: boolean;\n asTextWithSpoilers?: boolean;\n}\n\nconst MAX_LENGTH = 32;\nconst NBSP = '\\u00A0';\n\nexport function renderActionMessageText(\n lang: LangFn,\n message: ApiMessage,\n actionOriginUser?: ApiUser,\n actionOriginChat?: ApiChat,\n targetUsers?: ApiUser[],\n targetMessage?: ApiMessage,\n targetChatId?: string,\n options: RenderOptions = {},\n) {\n if (!message.content.action) {\n return [];\n }\n\n const {\n text, translationValues, amount, currency, call,\n } = message.content.action;\n const content: TextPart[] = [];\n const noLinks = options.asPlainText || options.asTextWithSpoilers;\n const translationKey = text === 'Chat.Service.Group.UpdatedPinnedMessage1' && !targetMessage\n ? 'Message.PinnedGenericMessage'\n : text;\n\n let unprocessed = lang(translationKey, 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 actionOriginUser ? (\n renderUserContent(actionOriginUser, noLinks) || NBSP\n ) : actionOriginChat ? (\n renderChatContent(lang, actionOriginChat, noLinks) || 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, noLinks)).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, options)\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, noLinks)\n : 'another chat',\n );\n content.push(...processed);\n\n if (options.asPlainText) {\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: RenderOptions = {}) {\n const { asPlainText, asTextWithSpoilers } = options;\n\n if (asPlainText) {\n return getMessageSummaryText(lang, message, undefined, MAX_LENGTH);\n }\n\n const messageSummary = renderMessageSummary(lang, message, undefined, undefined, MAX_LENGTH);\n\n if (asTextWithSpoilers) {\n return (\n {messageSummary}\n );\n }\n\n return (\n {messageSummary}\n );\n}\n\nfunction renderGroupCallContent(groupCall: Partial, text: TextPart[]): string | TextPart | undefined {\n return (\n \n {text}\n \n );\n}\n\nfunction renderUserContent(sender: ApiUser, noLinks?: boolean): string | TextPart | undefined {\n const text = trimText(getUserFullName(sender), MAX_LENGTH);\n\n if (noLinks) {\n return text;\n }\n\n return {sender && renderText(text!)};\n}\n\nfunction renderChatContent(lang: LangFn, chat: ApiChat, noLinks?: boolean): string | TextPart | undefined {\n const text = trimText(getChatTitle(lang, chat), MAX_LENGTH);\n\n if (noLinks) {\n return text;\n }\n\n return {chat && renderText(text!)};\n}\n\nfunction renderMigratedContent(chatId: string, noLinks?: boolean): string | TextPart | undefined {\n const text = 'another chat';\n\n if (noLinks) {\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 { ApiMessage, ApiMessageEntityTypes } from '../../../api/types';\nimport {\n getMessageSummaryDescription,\n getMessageSummaryEmoji,\n getMessageSummaryText,\n getMessageText,\n TRUNCATED_SUMMARY_LENGTH,\n} from '../../../global/helpers';\nimport { LangFn } from '../../../hooks/useLang';\nimport renderText from './renderText';\nimport { renderTextWithEntities, TextPart } from './renderTextWithEntities';\nimport trimText from '../../../util/trimText';\n\nexport type { TextPart };\n\nexport function renderMessageText(\n message: ApiMessage,\n highlight?: string,\n shouldRenderHqEmoji?: boolean,\n isSimple?: boolean,\n truncateLength?: number,\n) {\n const { text, entities } = message.content.text || {};\n\n if (!text) {\n const contentNotSupportedText = getMessageText(message);\n return contentNotSupportedText ? [trimText(contentNotSupportedText, truncateLength)] : undefined;\n }\n\n return renderTextWithEntities(\n trimText(text, truncateLength),\n entities,\n highlight,\n shouldRenderHqEmoji,\n undefined,\n message.id,\n isSimple,\n );\n}\n\nexport function renderMessageSummary(\n lang: LangFn,\n message: ApiMessage,\n noEmoji = false,\n highlight?: string,\n truncateLength = TRUNCATED_SUMMARY_LENGTH,\n): TextPart[] {\n const { entities } = message.content.text || {};\n\n const hasSpoilers = entities?.some((e) => e.type === ApiMessageEntityTypes.Spoiler);\n if (!hasSpoilers) {\n const text = trimText(getMessageSummaryText(lang, message, noEmoji), truncateLength);\n\n if (highlight) {\n return renderText(text, ['emoji', 'highlight'], { highlight });\n } else {\n return renderText(text);\n }\n }\n\n const emoji = !noEmoji && getMessageSummaryEmoji(message);\n const emojiWithSpace = emoji ? `${emoji} ` : '';\n\n const text = renderMessageText(message, highlight, undefined, true, truncateLength);\n const description = getMessageSummaryDescription(lang, message, text);\n\n return [\n emojiWithSpace,\n ...(Array.isArray(description) ? description : [description]),\n ].filter(Boolean);\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';\nimport { compact } from '../../../util/iteratees';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\n\ntype TextPart = string | Element;\nexport type TextFilter = (\n 'escape_html' | 'hq_emoji' | 'emoji' | 'emoji_html' | 'br' | 'br_html' | 'highlight' | 'links' |\n 'simple_markdown' | 'simple_markdown_html'\n);\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 = ['emoji'],\n params?: { highlight: string | undefined },\n): TextPart[] {\n if (typeof part !== 'string') {\n return [part];\n }\n\n return compact(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 { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect, useRef,\n} from '../../../lib/teact/teact';\n\nimport { createClassNameBuilder } from '../../../util/buildClassName';\nimport useFlag from '../../../hooks/useFlag';\n\nimport './Spoiler.scss';\n\ntype OwnProps = {\n children?: React.ReactNode;\n messageId?: number;\n};\n\nconst READING_SYMBOLS_PER_SECOND = 23; // Heuristics\nconst MIN_HIDE_TIMEOUT = 5000; // 5s\nconst MAX_HIDE_TIMEOUT = 60000; // 1m\n\nconst actionsByMessageId: Map = new Map();\n\nconst buildClassName = createClassNameBuilder('Spoiler');\n\nconst Spoiler: FC = ({\n children,\n messageId,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const contentRef = useRef(null);\n\n const [isRevealed, reveal, conceal] = useFlag();\n\n const handleClick = useCallback((e: ReactMouseEvent) => {\n e.preventDefault();\n e.stopPropagation();\n\n actionsByMessageId.get(messageId!)?.forEach((actions) => actions.reveal());\n\n const contentLength = contentRef.current!.innerText.length;\n const readingMs = Math.round(contentLength / READING_SYMBOLS_PER_SECOND) * 1000;\n const timeoutMs = Math.max(MIN_HIDE_TIMEOUT, Math.min(readingMs, MAX_HIDE_TIMEOUT));\n\n setTimeout(() => {\n actionsByMessageId.get(messageId!)?.forEach((actions) => actions.conceal());\n conceal();\n }, timeoutMs);\n }, [conceal, messageId]);\n\n useEffect(() => {\n if (!messageId) {\n return undefined;\n }\n\n if (actionsByMessageId.has(messageId)) {\n actionsByMessageId.get(messageId)!.push({ reveal, conceal });\n } else {\n actionsByMessageId.set(messageId, [{ reveal, conceal }]);\n }\n\n return () => {\n actionsByMessageId.delete(messageId);\n };\n }, [conceal, handleClick, isRevealed, messageId, reveal]);\n\n return (\n \n \n {children}\n \n
\n );\n};\n\nexport default memo(Spoiler);\n","import { MouseEvent } from 'react';\nimport React from '../../../lib/teact/teact';\nimport { getActions } from '../../../global';\n\nimport { ApiFormattedText, ApiMessageEntity, ApiMessageEntityTypes } from '../../../api/types';\nimport renderText, { TextFilter } from './renderText';\nimport { copyTextToClipboard } from '../../../util/clipboard';\nimport { getTranslation } from '../../../util/langProvider';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\nimport Spoiler from '../spoiler/Spoiler';\n\nexport type TextPart =\n string\n | Element;\n\ninterface IOrganizedEntity {\n entity: ApiMessageEntity;\n organizedIndexes: Set;\n nestedEntities: IOrganizedEntity[];\n}\n\nexport function renderTextWithEntities(\n text: string,\n entities?: ApiMessageEntity[],\n highlight?: string,\n shouldRenderHqEmoji?: boolean,\n shouldRenderAsHtml?: boolean,\n messageId?: number,\n isSimple?: boolean,\n) {\n if (!entities || !entities.length) {\n return renderMessagePart(text, highlight, shouldRenderHqEmoji, shouldRenderAsHtml, isSimple);\n }\n\n const result: TextPart[] = [];\n let deleteLineBreakAfterPre = false;\n\n const organizedEntities = organizeEntities(entities);\n\n // Recursive function to render regular and nested entities\n function renderEntity(\n textPartStart: number,\n textPartEnd: number,\n organizedEntity: IOrganizedEntity,\n isLastEntity: boolean,\n ) {\n const renderResult: TextPart[] = [];\n const { entity, nestedEntities } = organizedEntity;\n const { offset, length, type } = entity;\n\n // Render text before the entity\n let textBefore = text.substring(textPartStart, offset);\n const textBeforeLength = textBefore.length;\n if (textBefore) {\n if (deleteLineBreakAfterPre && textBefore.length > 0 && textBefore[0] === '\\n') {\n textBefore = textBefore.substr(1);\n deleteLineBreakAfterPre = false;\n }\n if (textBefore) {\n renderResult.push(...renderMessagePart(\n textBefore, highlight, shouldRenderHqEmoji, shouldRenderAsHtml, isSimple,\n ) as TextPart[]);\n }\n }\n\n const entityStartIndex = textPartStart + textBeforeLength;\n const entityEndIndex = entityStartIndex + length;\n\n let entityContent: TextPart = text.substring(offset, offset + length);\n const nestedEntityContent: TextPart[] = [];\n\n if (deleteLineBreakAfterPre && entityContent.length > 0 && entityContent[0] === '\\n') {\n entityContent = entityContent.substr(1);\n deleteLineBreakAfterPre = false;\n }\n\n if (type === ApiMessageEntityTypes.Pre) {\n deleteLineBreakAfterPre = true;\n }\n\n // Render nested entities, if any\n if (nestedEntities.length) {\n let nestedIndex = entityStartIndex;\n\n nestedEntities.forEach((nestedEntity, nestedEntityIndex) => {\n const {\n renderResult: nestedResult,\n entityEndIndex: nestedEntityEndIndex,\n } = renderEntity(\n nestedIndex,\n entityEndIndex,\n nestedEntity,\n nestedEntityIndex === nestedEntities.length - 1,\n );\n\n nestedEntityContent.push(...nestedResult);\n nestedIndex = nestedEntityEndIndex;\n });\n }\n\n // Render the entity itself\n const newEntity = shouldRenderAsHtml\n ? processEntityAsHtml(entity, entityContent, nestedEntityContent)\n : processEntity(entity, entityContent, nestedEntityContent, highlight, messageId, isSimple);\n\n if (Array.isArray(newEntity)) {\n renderResult.push(...newEntity);\n } else {\n renderResult.push(newEntity);\n }\n\n // Render text after the entity, if it is the last entity in the text,\n // or the last nested entity inside of another entity\n if (isLastEntity && entityEndIndex < textPartEnd) {\n let textAfter = text.substring(entityEndIndex, textPartEnd);\n if (deleteLineBreakAfterPre && textAfter.length > 0 && textAfter[0] === '\\n') {\n textAfter = textAfter.substring(1);\n }\n if (textAfter) {\n renderResult.push(...renderMessagePart(\n textAfter, highlight, shouldRenderHqEmoji, shouldRenderAsHtml, isSimple,\n ) as TextPart[]);\n }\n }\n\n return {\n renderResult,\n entityEndIndex,\n };\n }\n\n // Process highest-level entities\n let index = 0;\n\n organizedEntities.forEach((entity, arrayIndex) => {\n const { renderResult, entityEndIndex } = renderEntity(\n index,\n text.length,\n entity,\n arrayIndex === organizedEntities.length - 1,\n );\n\n result.push(...renderResult);\n index = entityEndIndex;\n });\n\n return result;\n}\n\nexport function getTextWithEntitiesAsHtml(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\nfunction renderMessagePart(\n content: TextPart | TextPart[],\n highlight?: string,\n shouldRenderHqEmoji?: boolean,\n shouldRenderAsHtml?: boolean,\n isSimple?: boolean,\n) {\n if (Array.isArray(content)) {\n const result: TextPart[] = [];\n\n content.forEach((c) => {\n result.push(...renderMessagePart(c, highlight, shouldRenderHqEmoji, shouldRenderAsHtml, isSimple));\n });\n\n return result;\n }\n\n if (shouldRenderAsHtml) {\n return renderText(content, ['escape_html', 'emoji_html', 'br_html']);\n }\n\n const emojiFilter = shouldRenderHqEmoji ? 'hq_emoji' : 'emoji';\n\n const filters: TextFilter[] = [emojiFilter];\n if (!isSimple) {\n filters.push('br');\n }\n\n if (highlight) {\n return renderText(content, filters.concat('highlight'), { highlight });\n } else {\n return renderText(content, filters);\n }\n}\n\n// Organize entities in a tree-like structure to better represent how the text will be displayed\nfunction organizeEntities(entities: ApiMessageEntity[]) {\n const organizedEntityIndexes: Set = new Set();\n const organizedEntities: IOrganizedEntity[] = [];\n\n entities.forEach((entity, index) => {\n if (organizedEntityIndexes.has(index)) {\n return;\n }\n\n const organizedEntity = organizeEntity(entity, index, entities, organizedEntityIndexes);\n if (organizedEntity) {\n organizedEntity.organizedIndexes.forEach((organizedIndex) => {\n organizedEntityIndexes.add(organizedIndex);\n });\n\n organizedEntities.push(organizedEntity);\n }\n });\n\n return organizedEntities;\n}\n\nfunction organizeEntity(\n entity: ApiMessageEntity,\n index: number,\n entities: ApiMessageEntity[],\n organizedEntityIndexes: Set,\n): IOrganizedEntity | undefined {\n const { offset, length } = entity;\n const organizedIndexes = new Set([index]);\n\n if (organizedEntityIndexes.has(index)) {\n return undefined;\n }\n\n // Determine any nested entities inside current entity\n const nestedEntities: IOrganizedEntity[] = [];\n const parsedNestedEntities = entities\n .filter((e, i) => i > index && e.offset >= offset && e.offset < offset + length)\n .map((e) => organizeEntity(e, entities.indexOf(e), entities, organizedEntityIndexes))\n .filter(Boolean as any);\n\n parsedNestedEntities.forEach((parsedEntity) => {\n let isChanged = false;\n\n parsedEntity.organizedIndexes.forEach((organizedIndex) => {\n if (!isChanged && !organizedIndexes.has(organizedIndex)) {\n isChanged = true;\n }\n\n organizedIndexes.add(organizedIndex);\n });\n\n if (isChanged) {\n nestedEntities.push(parsedEntity);\n }\n });\n\n return {\n entity,\n organizedIndexes,\n nestedEntities,\n };\n}\n\nfunction processEntity(\n entity: ApiMessageEntity,\n entityContent: TextPart,\n nestedEntityContent: TextPart[],\n highlight?: string,\n messageId?: number,\n isSimple?: boolean,\n) {\n const entityText = typeof entityContent === 'string' && entityContent;\n const renderedContent = nestedEntityContent.length ? nestedEntityContent : entityContent;\n\n function renderNestedMessagePart() {\n return renderMessagePart(\n renderedContent, highlight, undefined, undefined, isSimple,\n );\n }\n\n if (!entityText) {\n return renderNestedMessagePart();\n }\n\n if (isSimple) {\n const text = renderNestedMessagePart();\n if (entity.type === ApiMessageEntityTypes.Spoiler) {\n return {text};\n }\n return text;\n }\n\n switch (entity.type) {\n case ApiMessageEntityTypes.Bold:\n return {renderNestedMessagePart()};\n case ApiMessageEntityTypes.Blockquote:\n return
{renderNestedMessagePart()}
;\n case ApiMessageEntityTypes.BotCommand:\n return (\n \n {renderNestedMessagePart()}\n \n );\n case ApiMessageEntityTypes.Hashtag:\n return (\n \n {renderNestedMessagePart()}\n \n );\n case ApiMessageEntityTypes.Cashtag:\n return (\n \n {renderNestedMessagePart()}\n \n );\n case ApiMessageEntityTypes.Code:\n return (\n \n {renderNestedMessagePart()}\n \n );\n case ApiMessageEntityTypes.Email:\n return (\n \n {renderNestedMessagePart()}\n \n );\n case ApiMessageEntityTypes.Italic:\n return {renderNestedMessagePart()};\n case ApiMessageEntityTypes.MentionName:\n return (\n \n {renderNestedMessagePart()}\n \n );\n case ApiMessageEntityTypes.Mention:\n return (\n \n {renderNestedMessagePart()}\n \n );\n case ApiMessageEntityTypes.Phone:\n return (\n \n {renderNestedMessagePart()}\n \n );\n case ApiMessageEntityTypes.Pre:\n return
{renderNestedMessagePart()}
;\n case ApiMessageEntityTypes.Strike:\n return {renderNestedMessagePart()};\n case ApiMessageEntityTypes.TextUrl:\n case ApiMessageEntityTypes.Url:\n return (\n \n {renderNestedMessagePart()}\n \n );\n case ApiMessageEntityTypes.Underline:\n return {renderNestedMessagePart()};\n case ApiMessageEntityTypes.Spoiler:\n return {renderNestedMessagePart()};\n default:\n return renderNestedMessagePart();\n }\n}\n\nfunction processEntityAsHtml(\n entity: ApiMessageEntity,\n entityContent: TextPart,\n nestedEntityContent: TextPart[],\n) {\n const rawEntityText = typeof entityContent === 'string' && entityContent;\n\n const renderedContent = nestedEntityContent.length\n ? nestedEntityContent.join('')\n : renderText(entityContent, ['escape_html', 'emoji_html', 'br_html']).join('');\n\n if (!rawEntityText) {\n return renderedContent;\n }\n\n switch (entity.type) {\n case ApiMessageEntityTypes.Bold:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Italic:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Underline:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Code:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Pre:\n return `\\`\\`\\`
${renderedContent}
\\`\\`\\``;\n case ApiMessageEntityTypes.Strike:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.MentionName:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Url:\n case ApiMessageEntityTypes.TextUrl:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Spoiler:\n return `${renderedContent}
`;\n default:\n return renderedContent;\n }\n}\n\nfunction getLinkUrl(entityContent: string, entity: ApiMessageEntity) {\n const { type, url } = entity;\n return type === ApiMessageEntityTypes.TextUrl && url ? url : entityContent;\n}\n\nfunction handleBotCommandClick(e: MouseEvent) {\n getActions().sendBotCommand({ command: e.currentTarget.innerText });\n}\n\nfunction handleHashtagClick(e: MouseEvent) {\n getActions().setLocalTextSearchQuery({ query: e.currentTarget.innerText });\n getActions().searchTextMessagesLocal();\n}\n\nfunction handleCodeClick(e: MouseEvent) {\n copyTextToClipboard(e.currentTarget.innerText);\n getActions().showNotification({\n message: getTranslation('TextCopied'),\n });\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 { getActions, withGlobal } from '../../../global';\n\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport { selectUser } from '../../../global/selectors';\n\ntype OwnProps = {\n userId?: string;\n username?: string;\n children: React.ReactNode;\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 } = getActions();\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: React.ReactNode;\n size?: 'default' | 'smaller' | 'tiny';\n color?: (\n 'primary' | 'secondary' | 'gray' | 'danger' | 'translucent' | 'translucent-white' | 'translucent-black' | 'dark'\n );\n backgroundImage?: string;\n id?: string;\n className?: string;\n round?: boolean;\n pill?: boolean;\n fluid?: boolean;\n isText?: boolean;\n isLoading?: boolean;\n ariaLabel?: string;\n ariaControls?: string;\n hasPopup?: boolean;\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 id,\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 ariaControls,\n hasPopup,\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 id={id}\n className={fullClassName}\n href={href}\n title={ariaLabel}\n download={download}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n aria-label={ariaLabel}\n aria-controls={ariaControls}\n >\n {children}\n {!disabled && ripple && (\n \n )}\n \n );\n }\n\n return (\n }\n id={id}\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 aria-controls={ariaControls}\n aria-haspopup={hasPopup}\n title={ariaLabel}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\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 tabIndex?: number;\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 tabIndex,\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: React.ReactNode;\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 {\n ChangeEvent, FormEvent, RefObject,\n} 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 tabIndex?: 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 tabIndex,\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: React.ReactNode;\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';\nimport buildClassName from '../../util/buildClassName';\n\nimport './Loading.scss';\n\ntype OwnProps = {\n color?: 'blue' | 'white' | 'black' | 'yellow';\n backgroundColor?: 'light' | 'dark';\n onClick?: NoneToVoidFunction;\n};\n\nconst Loading: FC = ({ color = 'blue', backgroundColor, onClick }) => {\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';\nimport { IS_BACKDROP_BLUR_SUPPORTED, IS_COMPACT_MENU } from '../../util/environment';\n\nimport './Menu.scss';\n\ntype OwnProps = {\n ref?: RefObject;\n containerRef?: RefObject;\n isOpen: boolean;\n id?: string;\n className?: string;\n style?: string;\n bubbleStyle?: string;\n ariaLabelledBy?: string;\n transformOriginX?: number;\n transformOriginY?: number;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n autoClose?: boolean;\n shouldSkipTransition?: boolean;\n footer?: string;\n noCloseOnBackdrop?: boolean;\n noCompact?: 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: React.ReactNode;\n};\n\nconst ANIMATION_DURATION = 200;\n\nconst Menu: FC = ({\n ref,\n containerRef,\n isOpen,\n id,\n className,\n style,\n bubbleStyle,\n ariaLabelledBy,\n children,\n transformOriginX,\n transformOriginY,\n positionX = 'left',\n positionY = 'top',\n autoClose = false,\n footer,\n noCloseOnBackdrop = false,\n noCompact,\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 (isOpen || (!isOpen && prevIsOpen === true)) {\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 const transformOriginYStyle = transformOriginY !== undefined ? `${transformOriginY}px` : undefined;\n const transformOriginXStyle = transformOriginX !== undefined ? `${transformOriginX}px` : undefined;\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';\nimport { IS_COMPACT_MENU } from '../../util/environment';\n\nimport './MenuItem.scss';\n\ntype OnClickHandler = (e: React.SyntheticEvent) => void;\n\ntype OwnProps = {\n icon?: string;\n className?: string;\n children: React.ReactNode;\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 IS_COMPACT_MENU && 'compact',\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' | 'yellow';\n backgroundColor?: 'light' | 'dark';\n}> = ({\n color = 'blue',\n backgroundColor,\n}) => {\n return (\n
\n
\n
\n );\n};\n\nexport default Spinner;\n","export const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION!;\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 PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const DEBUG_PAYMENT_SMART_GLOCAL = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 500;\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 200;\nexport const GLOBAL_STATE_CACHE_CHATS_WITH_MESSAGES_LIMIT = 30;\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-v8';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const AUTODOWNLOAD_FILESIZE_MB_LIMITS = [1, 5, 10, 50, 100, 500];\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\nexport const GROUP_CALL_PARTICIPANTS_LIMIT = 100;\nexport const REACTION_LIST_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\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\nexport const CUSTOM_APPENDIX_ATTRIBUTE = 'data-has-custom-appendix';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const 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 = 100;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const STICKER_SIZE_JOIN_REQUESTS = 140;\nexport const STICKER_SIZE_INVITES = 140;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const NO_STICKER_SET_ID = 'NO_STICKER_SET';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\nexport const VIDEO_WEBM_TYPE = 'video/webm';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const 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\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 { addActionHandler, getActions, getGlobal } from '../../index';\n\nimport { initApi, callApi } from '../../../api/gramjs';\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, IS_WEBM_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\naddActionHandler('initApi', async (global, actions) => {\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 isWebmSupported: IS_WEBM_SUPPORTED,\n });\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('uploadProfilePhoto', (global, actions, payload) => {\n const { file } = payload!;\n\n void callApi('uploadProfilePhoto', file);\n});\n\naddActionHandler('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\naddActionHandler('returnToAuthPhoneNumber', (global) => {\n void callApi('restartAuth');\n\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddActionHandler('goToAuthQrCode', (global) => {\n void callApi('restartAuthWithQr');\n\n return {\n ...global,\n authIsLoadingQrCode: true,\n authError: undefined,\n };\n});\n\naddActionHandler('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\naddActionHandler('signOut', async (_global, _actions, payload) => {\n try {\n await unsubscribe();\n await callApi('destroy');\n await forceWebsync(false);\n } catch (err) {\n // Do nothing\n }\n\n getActions().reset();\n\n if (payload?.forceInitApi) {\n getActions().initApi();\n }\n});\n\naddActionHandler('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 getActions().init();\n});\n\naddActionHandler('disconnect', () => {\n void callApi('disconnect');\n});\n\naddActionHandler('loadNearestCountry', async (global) => {\n if (global.connectionState !== 'connectionStateReady') {\n return undefined;\n }\n\n const authNearestCountry = await callApi('fetchNearestCountry');\n\n return {\n ...getGlobal(),\n authNearestCountry,\n };\n});\n\naddActionHandler('setDeviceToken', (global, actions, deviceToken) => {\n return {\n ...global,\n push: {\n deviceToken,\n subscribedAt: Date.now(),\n },\n };\n});\n\naddActionHandler('deleteDeviceToken', (global) => {\n return {\n ...global,\n push: undefined,\n };\n});\n","import { addActionHandler, getGlobal, setGlobal } from '../../index';\n\nimport { GlobalState } from '../../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\naddActionHandler('updateProfile', async (global, actions, payload) => {\n const {\n photo, firstName, lastName, bio: about, username,\n } = payload!;\n\n const { currentUserId } = global;\n if (!currentUserId) {\n return undefined;\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 return {\n ...getGlobal(),\n profileEdit: {\n progress: ProfileEditProgress.Complete,\n },\n };\n});\n\naddActionHandler('checkUsername', async (global, actions, payload) => {\n const { username } = payload!;\n\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 undefined;\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 return {\n ...global,\n profileEdit: {\n ...global.profileEdit!,\n isUsernameAvailable,\n },\n };\n});\n\naddActionHandler('loadWallpapers', async () => {\n const result = await callApi('fetchWallpapers');\n if (!result) {\n return undefined;\n }\n\n const global = getGlobal();\n return {\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: result.wallpapers,\n },\n };\n});\n\naddActionHandler('uploadWallpaper', async (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 const result = await callApi('uploadWallpaper', file);\n if (!result) {\n return undefined;\n }\n\n const { wallpaper } = result;\n\n global = getGlobal();\n if (!global.settings.loadedWallpapers) {\n return undefined;\n }\n\n const firstWallpaper = global.settings.loadedWallpapers[0];\n if (!firstWallpaper || firstWallpaper.slug !== UPLOADING_WALLPAPER_SLUG) {\n return undefined;\n }\n\n const withLocalMedia = {\n ...wallpaper,\n document: {\n ...wallpaper.document,\n previewBlobUrl,\n },\n };\n\n return {\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: [\n withLocalMedia,\n ...global.settings.loadedWallpapers.slice(1),\n ],\n },\n };\n});\n\naddActionHandler('loadBlockedContacts', async (global) => {\n const result = await callApi('fetchBlockedContacts');\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n\n if (result.users?.length) {\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n }\n if (result.chats?.length) {\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n }\n\n global = {\n ...global,\n blocked: {\n ...global.blocked,\n ids: [...(global.blocked.ids || []), ...result.blockedIds],\n totalCount: result.totalCount,\n },\n };\n\n return global;\n});\n\naddActionHandler('blockContact', async (global, actions, payload) => {\n const { contactId, accessHash } = payload!;\n\n const result = await callApi('blockContact', contactId, accessHash);\n if (!result) {\n return undefined;\n }\n\n return addBlockedContact(getGlobal(), contactId);\n});\n\naddActionHandler('unblockContact', async (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 undefined;\n }\n\n accessHash = user.accessHash;\n }\n\n const result = await callApi('unblockContact', contactId, accessHash);\n if (!result) {\n return undefined;\n }\n\n return removeBlockedContact(getGlobal(), contactId);\n});\n\naddActionHandler('loadAuthorizations', async () => {\n const result = await callApi('fetchAuthorizations');\n if (!result) {\n return undefined;\n }\n\n return {\n ...getGlobal(),\n activeSessions: result,\n };\n});\n\naddActionHandler('terminateAuthorization', async (global, actions, payload) => {\n const { hash } = payload!;\n\n const result = await callApi('terminateAuthorization', hash);\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n\n return {\n ...global,\n activeSessions: global.activeSessions.filter((session) => session.hash !== hash),\n };\n});\n\naddActionHandler('terminateAllAuthorizations', async (global) => {\n const result = await callApi('terminateAllAuthorizations');\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n\n return {\n ...global,\n activeSessions: global.activeSessions.filter((session) => session.isCurrent),\n };\n});\n\naddActionHandler('loadNotificationExceptions', async (global) => {\n const { serverTimeOffset } = global;\n\n const result = await callApi('fetchNotificationExceptions', { serverTimeOffset });\n if (!result) {\n return undefined;\n }\n\n return addNotifyExceptions(getGlobal(), result);\n});\n\naddActionHandler('loadNotificationSettings', async (global) => {\n const { serverTimeOffset } = global;\n const result = await callApi('fetchNotificationSettings', {\n serverTimeOffset,\n });\n if (!result) {\n return undefined;\n }\n\n return replaceSettings(getGlobal(), result);\n});\n\naddActionHandler('updateNotificationSettings', async (global, actions, payload) => {\n const { peerType, isSilent, shouldShowPreviews } = payload!;\n\n const result = await callApi('updateNotificationSettings', peerType, { isSilent, shouldShowPreviews });\n if (!result) {\n return undefined;\n }\n\n return updateNotifySettings(getGlobal(), peerType, isSilent, shouldShowPreviews);\n});\n\naddActionHandler('updateWebNotificationSettings', (global, actions, payload) => {\n setGlobal(replaceSettings(global, payload));\n\n const { hasPushNotifications, hasWebNotifications } = global.settings.byKey;\n if (hasWebNotifications && hasPushNotifications) {\n void subscribe();\n } else {\n void unsubscribe();\n }\n});\n\naddActionHandler('updateContactSignUpNotification', async (global, actions, payload) => {\n const { isSilent } = payload!;\n\n const result = await callApi('updateContactSignUpNotification', isSilent);\n if (!result) {\n return undefined;\n }\n\n return replaceSettings(getGlobal(), { hasContactJoinedNotifications: !isSilent });\n});\n\naddActionHandler('loadLanguages', async () => {\n const result = await callApi('fetchLanguages');\n if (!result) {\n return undefined;\n }\n\n return replaceSettings(getGlobal(), { languages: result });\n});\n\naddActionHandler('loadPrivacySettings', async (global) => {\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 undefined;\n }\n\n 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 return global;\n});\n\naddActionHandler('setPrivacyVisibility', async (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 undefined;\n }\n\n const rules = buildInputPrivacyRules(global, {\n visibility,\n allowedIds: [...settings.allowUserIds, ...settings.allowChatIds],\n deniedIds: [...settings.blockUserIds, ...settings.blockChatIds],\n });\n\n const result = await callApi('setPrivacySettings', privacyKey, rules);\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n\n return {\n ...global,\n settings: {\n ...global.settings,\n privacy: {\n ...global.settings.privacy,\n [privacyKey]: result,\n },\n },\n };\n});\n\naddActionHandler('setPrivacySettings', async (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 undefined;\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 const result = await callApi('setPrivacySettings', privacyKey, rules);\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n\n return {\n ...global,\n settings: {\n ...global.settings,\n privacy: {\n ...global.settings.privacy,\n [privacyKey]: result,\n },\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\naddActionHandler('updateIsOnline', (global, actions, payload) => {\n callApi('updateIsOnline', payload);\n});\n\naddActionHandler('loadContentSettings', async () => {\n const result = await callApi('fetchContentSettings');\n if (!result) return undefined;\n\n return replaceSettings(getGlobal(), result);\n});\n\naddActionHandler('updateContentSettings', async (global, actions, payload) => {\n setGlobal(replaceSettings(getGlobal(), { isSensitiveEnabled: payload }));\n\n const result = await callApi('updateContentSettings', payload);\n if (!result) {\n return replaceSettings(getGlobal(), { isSensitiveEnabled: !payload });\n }\n\n return undefined;\n});\n\naddActionHandler('loadCountryList', async (global, actions, payload = {}) => {\n let { langCode } = payload;\n if (!langCode) langCode = global.settings.byKey.language;\n\n const countryList = await callApi('fetchCountryList', { langCode });\n if (!countryList) return undefined;\n\n return {\n ...getGlobal(),\n countryList,\n };\n});\n\naddActionHandler('ensureTimeFormat', async (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 if (global.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\naddActionHandler('loadAppConfig', async () => {\n const appConfig = await callApi('fetchAppConfig');\n if (!appConfig) return undefined;\n\n return {\n ...getGlobal(),\n appConfig,\n };\n});\n","import {\n addActionHandler, getActions, getGlobal, setGlobal,\n} from '../../index';\n\nimport { GlobalState } from '../../types';\n\nimport {\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\naddActionHandler('apiUpdate', (global, actions, update) => {\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 });\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 if (connectionState === global.connectionState) {\n return;\n }\n\n setGlobal({\n ...global,\n connectionState,\n });\n\n if (connectionState === 'connectionStateBroken') {\n // When mounting Auth `initApi` will be called from an effect. Otherwise, we force it here.\n const isOnAuth = !global.authState || [\n 'authorizationStateWaitPhoneNumber',\n 'authorizationStateWaitCode',\n 'authorizationStateWaitPassword',\n 'authorizationStateWaitRegistration',\n 'authorizationStateWaitQrCode',\n ].includes(global.authState);\n\n getActions().signOut({ forceInitApi: isOnAuth });\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 getActions().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 { addActionHandler, getGlobal, setGlobal } from '../../index';\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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n return {\n ...global,\n authPhoneNumber: phoneNumber,\n };\n});\n\naddActionHandler('setAuthRememberMe', (global, actions, payload) => {\n return {\n ...global,\n authRememberMe: Boolean(payload),\n };\n});\n\naddActionHandler('clearAuthError', (global) => {\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddActionHandler('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 { addActionHandler } from '../../index';\nimport { ISettings, IThemeSettings, ThemeKey } from '../../../types';\nimport { replaceSettings, replaceThemeSettings } from '../../reducers';\n\naddActionHandler('setSettingOption', (global, actions, payload?: Partial) => {\n return replaceSettings(global, payload);\n});\n\naddActionHandler('setThemeSettings', (global, actions, payload: { theme: ThemeKey } & Partial) => {\n const { theme, ...settings } = payload;\n\n return replaceThemeSettings(global, theme, settings);\n});\n","import {\n ApiChat,\n ApiUser,\n ApiChatBannedRights,\n ApiChatAdminRights,\n ApiChatFolder,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { NotifyException, NotifySettings } from '../../types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport { ARCHIVED_FOLDER_ID, REPLIES_USER_ID } from '../../config';\nimport { orderBy } from '../../util/iteratees';\nimport { getUserFirstOrLastName } from './users';\nimport { formatDateToString, formatTime } from '../../util/dateFormat';\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(lang, untilDate * 1000)],\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 getFolderDescriptionText(lang: LangFn, folder: ApiChatFolder, chatsCount?: number) {\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 chatsCount !== undefined && (\n Object.values(filters).filter(Boolean).length > 1\n || (excludedChatIds?.length)\n || (includedChatIds?.length)\n )) {\n return lang('Chats', chatsCount);\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\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, ApiReactions, ApiUser,\n} from '../../api/types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport {\n CONTENT_NOT_SUPPORTED,\n LOCAL_MESSAGE_ID_BASE,\n RE_LINK_TEMPLATE,\n SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../config';\nimport { getUserFullName } from './users';\nimport { IS_OPUS_SUPPORTED, isWebpSupported } 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');\n\nexport type MessageKey = `msg${string}-${number}`;\n\nexport function getMessageHtmlId(messageId: number) {\n return `message${messageId.toString().replace('.', '-')}`;\n}\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 getMessageText(message: ApiMessage) {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact, invoice, location,\n } = message.content;\n\n if (text) {\n return text.text;\n }\n\n if (sticker || photo || video || audio || voice || document\n || contact || poll || webPage || invoice || location) {\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 Boolean(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 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.isLottie ? 'tgs' : content.sticker.isVideo\n ? 'webm' : 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\nexport function areReactionsEmpty(reactions: ApiReactions) {\n return !reactions.results.some((l) => l.count > 0);\n}\n\nexport function isGeoLiveExpired(message: ApiMessage, timestamp = Date.now() / 1000) {\n const { location } = message.content;\n if (location?.type !== 'geoLive') return false;\n return (timestamp - (message.date || 0) >= location.period);\n}\n","import { ApiMessage, ApiReactions } from '../../api/types';\n\nexport function getMessageRecentReaction(message: Partial) {\n return message.isOutgoing ? message.reactions?.recentReactions?.[0] : undefined;\n}\n\nexport function checkIfReactionAdded(oldReactions?: ApiReactions, newReactions?: ApiReactions, currentUserId?: string) {\n if (!oldReactions || !oldReactions.recentReactions) return true;\n if (!newReactions || !newReactions.recentReactions) return false;\n // Skip reactions from yourself\n if (newReactions.recentReactions.every((reaction) => reaction.userId === currentUserId)) return false;\n const oldReactionsMap = oldReactions.results.reduce>((acc, reaction) => {\n acc[reaction.reaction] = reaction.count;\n return acc;\n }, {});\n return newReactions.results.some((r) => !oldReactionsMap[r.reaction] || oldReactionsMap[r.reaction] < r.count);\n}\n","import { ApiMessage, ApiMessageEntityTypes } from '../../api/types';\nimport type { TextPart } from '../../components/common/helpers/renderTextWithEntities';\nimport { CONTENT_NOT_SUPPORTED } from '../../config';\n\nimport { LangFn } from '../../hooks/useLang';\nimport trimText from '../../util/trimText';\nimport { getMessageText } from './messages';\nimport { getMessageRecentReaction } from './reactions';\n\nconst SPOILER_CHARS = ['⠺', '⠵', '⠞', '⠟'];\nexport const TRUNCATED_SUMMARY_LENGTH = 80;\n\nexport function getMessageSummaryText(\n lang: LangFn,\n message: ApiMessage,\n noEmoji = false,\n truncateLength = TRUNCATED_SUMMARY_LENGTH,\n noReactions = true,\n isExtended = false,\n) {\n const emoji = !noEmoji && getMessageSummaryEmoji(message, noReactions);\n const emojiWithSpace = emoji ? `${emoji} ` : '';\n const text = trimText(getMessageTextWithSpoilers(message), truncateLength);\n const description = getMessageSummaryDescription(lang, message, text, noReactions, isExtended);\n\n return `${emojiWithSpace}${description}`;\n}\n\nexport function getMessageTextWithSpoilers(message: ApiMessage) {\n const text = getMessageText(message);\n if (!text) {\n return undefined;\n }\n\n const { entities } = message.content.text || {};\n if (!entities?.length) {\n return text;\n }\n\n return entities.reduce((accText, {\n type,\n offset,\n length,\n }) => {\n if (type !== ApiMessageEntityTypes.Spoiler) {\n return accText;\n }\n\n const spoiler = generateBrailleSpoiler(length);\n\n return `${accText.substr(0, offset)}${spoiler}${accText.substr(offset + length, accText.length)}`;\n }, text);\n}\n\nexport function getMessageSummaryEmoji(message: ApiMessage, noReactions = true) {\n const {\n photo,\n video,\n audio,\n voice,\n document,\n sticker,\n poll,\n } = message.content;\n\n if (message.groupedId || photo) {\n return '🖼';\n }\n\n if (video) {\n return '📹';\n }\n\n if (sticker) {\n return sticker.emoji;\n }\n\n if (audio) {\n return '🎧';\n }\n\n if (voice) {\n return '🎤';\n }\n\n if (document) {\n return '📎';\n }\n\n if (poll) {\n return '📊';\n }\n\n const reaction = !noReactions && getMessageRecentReaction(message);\n if (reaction) {\n return reaction.reaction;\n }\n\n return undefined;\n}\n\nexport function getMessageSummaryDescription(\n lang: LangFn,\n message: ApiMessage,\n truncatedText?: string | TextPart[],\n noReactions = true,\n isExtended = false,\n) {\n const {\n text,\n photo,\n video,\n audio,\n voice,\n document,\n sticker,\n contact,\n poll,\n invoice,\n location,\n } = message.content;\n\n let summary: string | TextPart[] | undefined;\n\n if (message.groupedId) {\n summary = truncatedText || lang('lng_in_dlg_album');\n }\n\n if (photo) {\n summary = truncatedText || lang('AttachPhoto');\n }\n\n if (video) {\n summary = truncatedText || lang(video.isGif ? 'AttachGif' : 'AttachVideo');\n }\n\n if (sticker) {\n summary = lang('AttachSticker').trim();\n }\n\n if (audio) {\n summary = getMessageAudioCaption(message) || lang('AttachMusic');\n }\n\n if (voice) {\n summary = truncatedText || lang('AttachAudio');\n }\n\n if (document) {\n summary = isExtended ? document.fileName : (truncatedText || document.fileName);\n }\n\n if (contact) {\n summary = lang('AttachContact');\n }\n\n if (poll) {\n summary = poll.summary.question;\n }\n\n if (invoice) {\n summary = `${lang('PaymentInvoice')}: ${invoice.text}`;\n }\n\n if (text) {\n if (isExtended && summary) {\n summary += `\\n${truncatedText}`;\n } else {\n summary = truncatedText;\n }\n }\n\n if (location?.type === 'geo' || location?.type === 'venue') {\n summary = lang('Message.Location');\n }\n\n if (location?.type === 'geoLive') {\n summary = lang('Message.LiveLocation');\n }\n\n const reaction = !noReactions && getMessageRecentReaction(message);\n if (summary && reaction) {\n summary = `to your \"${summary}\"`;\n }\n\n return summary || CONTENT_NOT_SUPPORTED;\n}\n\nexport function generateBrailleSpoiler(length: number) {\n return new Array(length)\n .fill(undefined)\n .map(() => SPOILER_CHARS[Math.floor(Math.random() * SPOILER_CHARS.length)])\n .join('');\n}\n\nfunction getMessageAudioCaption(message: ApiMessage) {\n const {\n audio,\n text,\n } = message.content;\n\n return (audio && [audio.title, audio.performer].filter(Boolean)\n .join(' — ')) || (text?.text);\n}\n","import {\n ApiAudio, ApiMediaFormat, ApiMessage, ApiMessageSearchType, ApiPhoto, ApiVideo, ApiDimensions, ApiLocation,\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 getMessageLocation(message: ApiMessage) {\n return message.content.location;\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 buildStaticMapHash(\n geo: ApiLocation['geo'],\n width: number,\n height: number,\n zoom: number,\n scale: number,\n) {\n const {\n long, lat, accessHash, accuracyRadius,\n } = geo;\n\n // eslint-disable-next-line max-len\n return `staticMap:${accessHash}?lat=${lat}&long=${long}&w=${width}&h=${height}&zoom=${zoom}&scale=${scale}&accuracyRadius=${accuracyRadius}`;\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 const content = messagePhoto || messageVideo || sticker || audio || voice || document;\n\n if (!content) {\n return undefined;\n }\n\n const mediaId = content.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): 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.isLottie) {\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 return getMessageContentIds(messages, listedIds, isFromSharedMedia ? 'media' : 'inlineMedia');\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(lang, wasOnlineDate));\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(lang, wasOnlineDate));\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(\n userIds: string[],\n usersById: Record,\n query?: string,\n currentUserId?: string,\n savedMessagesLang?: string,\n) {\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 = id === currentUserId ? savedMessagesLang : 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 { typify } from '../lib/teact/teactn';\nimport { GlobalState, ActionPayloads, NonTypedActionNames } from './types';\n\nconst typed = typify();\n\nexport const getGlobal = typed.getGlobal;\nexport const setGlobal = typed.setGlobal;\nexport const getActions = typed.getActions;\nexport const addActionHandler = typed.addActionHandler;\nexport const withGlobal = typed.withGlobal;\n","import { GlobalState } from '../types';\nimport { ApiChat, ApiChatMember, ApiPhoto } from '../../api/types';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { areSortedArraysEqual, 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\nexport function addChatMembers(global: GlobalState, chat: ApiChat, membersToAdd: ApiChatMember[]): GlobalState {\n const currentMembers = chat.fullInfo?.members;\n const newMemberIds = new Set(membersToAdd.map((m) => m.userId));\n const updatedMembers = [\n ...currentMembers?.filter((m) => !newMemberIds.has(m.userId)) || [],\n ...membersToAdd,\n ];\n const currentIds = currentMembers?.map(({ userId }) => userId) || [];\n const updatedIds = updatedMembers.map(({ userId }) => userId);\n\n if (areSortedArraysEqual(currentIds, updatedIds)) {\n return global;\n }\n\n return updateChat(global, chat.id, {\n fullInfo: {\n ...chat.fullInfo,\n members: updatedMembers,\n },\n });\n}\n","import { GlobalState } from '../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 const addedSets = global.stickers.added.setIds || [];\n let setIds: string[] = addedSets;\n if (update.installedDate && addedSets && !addedSets.includes(stickerSetId)) {\n setIds = [stickerSetId, ...setIds];\n }\n\n if (!update.installedDate && addedSets?.includes(stickerSetId)) {\n setIds = setIds.filter((id) => id !== stickerSetId);\n }\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n added: {\n ...global.stickers.added,\n setIds,\n },\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 '../types';\nimport { ApiUser, ApiUserStatus } from '../../api/types';\n\nimport { omit, pick } from '../../util/iteratees';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\nimport { updateChat } from './chats';\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 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 global = replaceUsers(global, {\n ...byId,\n [userId]: {\n ...byId[userId],\n isContact: undefined,\n },\n });\n\n return updateChat(global, userId, {\n settings: undefined,\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\nexport function closeNewContactDialog(global: GlobalState): GlobalState {\n return {\n ...global,\n newContact: undefined,\n };\n}\n","import { GlobalState } from '../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 '../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) => b - a);\n}\n","import { GlobalState } from '../types';\nimport { ManagementProgress, ManagementState } from '../../types';\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 '../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\n// eslint-disable-next-line consistent-return\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}\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 '../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 '../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 setSmartGlocalCardInfo(\n global: GlobalState,\n cardInfo: { type: string; token: string },\n): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n smartGlocalCredentials: {\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 setConfirmPaymentUrl(global: GlobalState, url?: string): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n confirmPaymentUrl: url,\n },\n };\n}\n\nexport function setReceipt(\n global: GlobalState,\n receipt?: ApiReceipt,\n message?: ApiMessage,\n): GlobalState {\n if (!receipt || !message) {\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n };\n }\n\n const { invoice: messageInvoice } = message.content;\n const { photoUrl, text, title } = (messageInvoice || {});\n\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: {\n ...receipt,\n photoUrl,\n text,\n title,\n },\n },\n };\n}\n\nexport function clearPayment(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {},\n };\n}\n\nexport function closeInvoice(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n isPaymentModalOpen: false,\n },\n };\n}\n","import { GlobalState } from '../types';\nimport { ApiChannelStatistics, ApiGroupStatistics, StatisticsGraph } from '../../api/types';\n\nexport function updateStatistics(\n global: GlobalState, chatId: string, statistics: ApiChannelStatistics | ApiGroupStatistics,\n): GlobalState {\n return {\n ...global,\n statistics: {\n byChatId: {\n ...global.statistics.byChatId,\n [chatId]: statistics,\n },\n },\n };\n}\n\nexport function updateStatisticsGraph(\n global: GlobalState, chatId: string, name: string, update: StatisticsGraph,\n): GlobalState {\n return {\n ...global,\n statistics: {\n byChatId: {\n ...global.statistics.byChatId,\n [chatId]: {\n ...(global.statistics.byChatId[chatId] || {}),\n [name]: update,\n },\n },\n },\n };\n}\n","import {\n GlobalState, MessageList, MessageListType, Thread,\n} from '../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\nexport function 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 { ApiChat, MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalState } from '../types';\n\nimport {\n getPrivateChatUserId, isChatChannel, isUserId, isHistoryClearMessage, isUserBot, isUserOnline,\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';\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 Boolean(active?.includes(chatId));\n }\n\n if (folderId === ARCHIVED_FOLDER_ID) {\n return Boolean(archived?.includes(chatId));\n }\n\n const { byId: chatFoldersById } = global.chatFolders;\n\n const { pinnedChatIds } = chatFoldersById[folderId] || {};\n return Boolean(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\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 '../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\n stickersForEmoji = stickersForEmoji.concat(packs[emoji] || [], packs[cleanEmoji(emoji)] || []);\n });\n return stickersForEmoji;\n}\n\nfunction cleanEmoji(emoji: string) {\n // Some emojis (❤️ for example) with a service symbol 'VARIATION SELECTOR-16' are not recognized as animated\n return emoji.replace('\\ufe0f', '');\n}\n\nexport function selectAnimatedEmoji(global: GlobalState, emoji: string) {\n const { animatedEmojis } = global;\n if (!animatedEmojis || !animatedEmojis.stickers) {\n return undefined;\n }\n\n const cleanedEmoji = cleanEmoji(emoji);\n\n return animatedEmojis.stickers.find((sticker) => sticker.emoji === emoji || sticker.emoji === cleanedEmoji);\n}\n\nexport function selectAnimatedEmojiEffect(global: GlobalState, emoji: string) {\n const { animatedEmojiEffects } = global;\n if (!animatedEmojiEffects || !animatedEmojiEffects.stickers) {\n return undefined;\n }\n\n const cleanedEmoji = cleanEmoji(emoji);\n\n return animatedEmojiEffects.stickers.find((sticker) => sticker.emoji === emoji || sticker.emoji === cleanedEmoji);\n}\n\nexport function selectAnimatedEmojiSound(global: GlobalState, emoji: string) {\n return global?.appConfig?.emojiSounds[cleanEmoji(emoji)];\n}\n\nexport function selectLocalAnimatedEmoji(global: GlobalState, emoji: string) {\n const cleanedEmoji = cleanEmoji(emoji);\n\n return cleanedEmoji === '🍑' ? 'Peach' : (cleanedEmoji === '🍆' ? 'Eggplant' : undefined);\n}\n\nexport function selectLocalAnimatedEmojiEffect(emoji: string) {\n return emoji === 'Eggplant' ? 'Cumshot' : undefined;\n}\n\nexport function selectLocalAnimatedEmojiEffectByName(name: string) {\n return name === 'Cumshot' ? '🍆' : undefined;\n}\n","import { GlobalState, MessageListType, Thread } from '../types';\nimport {\n ApiChat,\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { LOCAL_MESSAGE_ID_BASE, REPLIES_USER_ID, SERVICE_NOTIFICATIONS_USER_ID } from '../../config';\nimport {\n selectChat, selectChatBot, selectIsChatWithBot, selectIsChatWithSelf,\n} from './chats';\nimport { selectIsUserOrChatContact, selectUser, selectUserStatus } 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 selectEditingDraft(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'editingDraft');\n}\n\nexport function selectEditingScheduledId(global: GlobalState, chatId: string) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'editingScheduledId');\n}\n\nexport function selectEditingScheduledDraft(global: GlobalState, chatId: string) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'editingScheduledDraft');\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 selectIsMessageInCurrentMessageList(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) || content.location\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 canSaveGif = message.content.video?.isGif;\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 canSaveGif,\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 canSaveGif,\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\nexport function selectDefaultReaction(global: GlobalState, chatId: string) {\n if (chatId === SERVICE_NOTIFICATIONS_USER_ID) return undefined;\n\n const isPrivate = isUserId(chatId);\n const defaultReaction = global.appConfig?.defaultReaction;\n const { availableReactions } = global;\n if (!defaultReaction || !availableReactions?.some(\n (l) => l.reaction === defaultReaction && !l.isInactive,\n )) {\n return undefined;\n }\n\n if (isPrivate) {\n return defaultReaction;\n }\n\n const enabledReactions = selectChat(global, chatId)?.fullInfo?.enabledReactions;\n if (!enabledReactions?.includes(defaultReaction)) {\n return undefined;\n }\n\n return defaultReaction;\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectVisibleUsers(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const messageIds = selectThreadParam(global, chatId, threadId, 'viewportIds');\n if (!messageIds) {\n return undefined;\n }\n\n return messageIds.map((messageId) => {\n const { senderId } = selectChatMessage(global, chatId, messageId) || {};\n return senderId ? selectUser(global, senderId) : undefined;\n }).filter(Boolean);\n}\n\nexport function selectShouldSchedule(global: GlobalState) {\n return selectCurrentMessageList(global)?.type === 'scheduled';\n}\n\nexport function selectCanScheduleUntilOnline(global: GlobalState, id: string) {\n const isChatWithSelf = selectIsChatWithSelf(global, id);\n const chatBot = id === REPLIES_USER_ID && selectChatBot(global, id);\n return Boolean(\n !isChatWithSelf && !chatBot && isUserId(id) && selectUserStatus(global, id)?.wasOnline,\n );\n}\n","import { GlobalState } from '../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 selectCurrentMediaSearch(global: GlobalState) {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return undefined;\n }\n\n return global.localMediaSearch.byChatId[chatId];\n}\n","import { GlobalState } from '../types';\n\nimport { selectCurrentMessageList } from './messages';\nimport { selectChat } from './chats';\n\nexport function selectStatistics(global: GlobalState, chatId: string) {\n return global.statistics.byChatId[chatId];\n}\n\nexport function selectIsStatisticsShown(global: GlobalState) {\n if (!global.isStatisticsShown) {\n return false;\n }\n\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const chat = currentChatId ? selectChat(global, currentChatId) : undefined;\n\n return chat?.fullInfo?.canViewStatistics;\n}\n","import { GlobalState } from '../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 '../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 { selectIsStatisticsShown } from './statistics';\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 return selectIsPollResultsOpen(global) ? (\n RightColumnContent.PollResults\n ) : !IS_SINGLE_COLUMN_LAYOUT && selectCurrentTextSearch(global) ? (\n RightColumnContent.Search\n ) : selectCurrentManagement(global) ? (\n RightColumnContent.Management\n ) : selectIsStatisticsShown(global) ? (\n RightColumnContent.Statistics\n ) : selectCurrentStickerSearch(global).query !== undefined ? (\n RightColumnContent.StickerSearch\n ) : selectCurrentGifSearch(global).query !== undefined ? (\n RightColumnContent.GifSearch\n ) : global.newChatMembersProgress !== NewChatMembersProgress.Closed ? (\n RightColumnContent.AddingMembers\n ) : global.isChatInfoShown && selectCurrentMessageList(global) ? (\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 '../types';\n\nexport function selectCurrentGlobalSearchQuery(global: GlobalState) {\n return global.globalSearch.query;\n}\n","import { GlobalState } from '../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?.publishableKey;\n}\n\nexport function selectProviderPublicToken(global: GlobalState) {\n return global.payment.nativeParams?.publicToken;\n}\n\nexport function selectStripeCredentials(global: GlobalState) {\n return global.payment.stripeCredentials;\n}\n\nexport function selectSmartGlocalCredentials(global: GlobalState) {\n return global.payment.smartGlocalCredentials;\n}\n","import { GlobalState } from '../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 '../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\n// Slow, not to be used in `withGlobal`\nexport function selectUserByPhoneNumber(global: GlobalState, phoneNumber: string) {\n const phoneNumberCleaned = phoneNumber.replace(/[^0-9]/g, '');\n\n return Object.values(global.users.byId).find((user) => user?.phoneNumber === phoneNumberCleaned);\n}\n\nexport function selectIsUserOrChatContact(global: GlobalState, userOrChat: ApiUser | ApiChat) {\n return global.contactList && global.contactList.userIds.includes(userOrChat.id);\n}\n","import { useEffect } from '../lib/teact/teact';\nimport usePrevious from './usePrevious';\n\nconst useEffectWithPrevDeps = (\n cb: (args: T | readonly []) => void, dependencies: T, debugKey?: string,\n) => {\n const prevDeps = usePrevious(dependencies);\n return useEffect(() => {\n return cb(prevDeps || []);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies, debugKey);\n};\n\nexport default useEffectWithPrevDeps;\n","import { useCallback, useState } from '../lib/teact/teact';\n\nconst useFlag = (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\nexport default useFlag;\n","import { useCallback, useState } from '../lib/teact/teact';\n\nconst useForceUpdate = () => {\n const [, setTrigger] = useState(false);\n\n return useCallback(() => {\n setTrigger((trigger) => !trigger);\n }, []);\n};\n\nexport default useForceUpdate;\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\nconst useHeavyAnimationCheck = (\n handleAnimationStart: AnyToVoidFunction,\n handleAnimationEnd: AnyToVoidFunction,\n isDisabled = false,\n) => {\n useEffect(() => {\n if (isDisabled) {\n return undefined;\n }\n\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 }, [isDisabled, 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\nexport default useHeavyAnimationCheck;\n","import { useCallback, useEffect, useRef } from '../lib/teact/teact';\n\nimport { IS_IOS } from '../util/environment';\nimport usePrevious from './usePrevious';\nimport { getActions } from '../global';\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 getActions()\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 getActions()\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\nconst useKeyboardListNavigation = (\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\nexport default useKeyboardListNavigation;\n","import * as langProvider from '../util/langProvider';\nimport useForceUpdate from './useForceUpdate';\nimport useOnChange from './useOnChange';\n\nexport type LangFn = typeof langProvider.getTranslation;\n\nconst useLang = (): LangFn => {\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n return langProvider.addCallback(forceUpdate);\n }, [forceUpdate]);\n\n return langProvider.getTranslation;\n};\n\nexport default useLang;\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\nconst useModuleLoader = >(\n bundleName: B, moduleName: M, noLoad = false, autoUpdate = false,\n) => {\n const module = getModuleFromMemory(bundleName, moduleName);\n const forceUpdate = useForceUpdate();\n\n useEffect(() => {\n if (!autoUpdate) {\n return undefined;\n }\n\n return addLoadListener(forceUpdate);\n }, [autoUpdate, forceUpdate]);\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\nexport default useModuleLoader;\n","import usePrevious from './usePrevious';\n\nconst useOnChange = (cb: (args: T | readonly []) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n if (!prevDeps || dependencies.some((d, i) => d !== prevDeps[i])) {\n cb(prevDeps || []);\n }\n};\n\nexport default useOnChange;\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\nconst useShowTransition = (\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 const exec = () => {\n setIsClosed(true);\n\n if (onCloseTransitionEnd) {\n onCloseTransitionEnd();\n }\n\n closeTimeoutRef.current = undefined;\n };\n\n if (noCloseTransition) {\n exec();\n } else {\n closeTimeoutRef.current = window.setTimeout(exec, CLOSE_DURATION);\n }\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\nexport default useShowTransition;\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 VirtualElementChildren,\n} from './teact';\nimport generateIdFor from '../../util/generateIdFor';\nimport { DEBUG } from '../../config';\nimport { addEventListener, removeEventListener } from './dom-events';\nimport { unique } from '../../util/iteratees';\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 const isCurrentComponent = $current && isComponentElement($current);\n const isNewComponent = $new && isComponentElement($new);\n\n if (\n !skipComponentUpdate\n && isCurrentComponent && isNewComponent\n && !hasElementChanged($current!, $new!)\n ) {\n $new = updateComponent($current as VirtualElementComponent, $new as VirtualElementComponent);\n }\n\n // Parent element may have changed, so we need to update the listener closure.\n if (!skipComponentUpdate && isNewComponent && ($new as VirtualElementComponent).componentInstance.isMounted) {\n setupComponentUpdateListener($new as VirtualElementComponent, $parent, index, parentEl);\n }\n\n if ($current === $new) {\n return $new;\n }\n\n if (DEBUG && $new) {\n const newTarget = getTarget($new);\n if (newTarget && (!$current || newTarget !== getTarget($current))) {\n throw new Error('[Teact] Cached virtual element was moved within tree');\n }\n }\n\n if (!$current && $new) {\n if (isNewComponent) {\n $new = initComponent($new as VirtualElementComponent, $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 (isNewComponent) {\n $new = initComponent($new as VirtualElementComponent, $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 = isCurrentComponent && isNewComponent;\n const currentTarget = getTarget($current);\n\n if (!areComponents) {\n setTarget($new, currentTarget!);\n setTarget($current, undefined as any); // Help GC\n\n if ('props' in $current && 'props' in $new) {\n $new.props.ref = $current.props.ref;\n }\n }\n\n if (isRealElement($new)) {\n if (moveDirection) {\n const node = currentTarget!;\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 as VirtualRealElement), $new, currentTarget as HTMLElement);\n }\n\n $new.children = renderChildren(\n ($current as VirtualRealElement),\n $new,\n areComponents ? parentEl : currentTarget 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.entries(props).forEach(([key, value]) => {\n if (props[key] !== undefined) {\n setAttribute(element, key, value);\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 (DEBUG) {\n DEBUG_checkKeyUniqueness($new.children);\n }\n\n if ($new.props.teactFastList) {\n return renderFastListChildren($current, $new, currentEl);\n }\n\n const currentChildrenLength = $current.children.length;\n const newChildrenLength = $new.children.length;\n const maxLength = Math.max(currentChildrenLength, newChildrenLength);\n const newChildren = [];\n const fragment = newChildrenLength > currentChildrenLength + 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 >= currentChildrenLength ? { 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 moveDirection: shouldMoveNode ? (isMovingDown ? 'down' : 'up') : undefined,\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 currentEntries = Object.entries($current.props);\n const newEntries = Object.entries($new.props);\n\n currentEntries.forEach(([key, currentValue]) => {\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 newEntries.forEach(([key, newValue]) => {\n const currentValue = $current.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 if ((element as HTMLInputElement).value !== value) {\n (element as HTMLInputElement).value = value;\n }\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\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction DEBUG_checkKeyUniqueness(children: VirtualElementChildren) {\n const firstChild = children[0];\n if (firstChild && 'props' in firstChild && firstChild.props.key !== undefined) {\n const keys = children.reduce((acc: any[], child) => {\n if ('props' in child && child.props.key) {\n acc.push(child.props.key);\n }\n\n return acc;\n }, []);\n\n if (keys.length !== unique(keys).length) {\n throw new Error('[Teact] Children keys are not unique');\n }\n }\n}\n\nconst TeactDOM = { render };\nexport default TeactDOM;\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 { 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?: readonly 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;\nconst DEBUG_SILENT_RENDERS_FOR = new Set(['TeactMemoWrapper', 'TeactNContainer', 'Button', 'ListItem', 'MenuItem']);\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 (!DEBUG_SILENT_RENDERS_FOR.has(componentName)) {\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: any) {\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 (isComponentElement($element)) {\n unmountComponent($element.componentInstance);\n } else {\n if (isTagElement($element)) {\n if ($element.target) {\n removeAllDelegatedListeners($element.target as HTMLElement);\n }\n\n if ($element.props.ref) {\n $element.props.ref.current = undefined; // Help GC\n }\n }\n\n if ($element.target) {\n $element.target = undefined; // Help GC\n }\n\n if (!isRealElement($element)) {\n return;\n }\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 // We need to clean refs before running effect cleanups\n componentInstance.hooks.memos.byCursor.forEach((memoContainer) => {\n memoContainer.current = undefined;\n });\n\n componentInstance.hooks.effects.byCursor.forEach(({ cleanup }) => {\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err: any) {\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 componentInstance.hooks.effects.byCursor.forEach((hook) => {\n hook.cleanup = undefined;\n hook.effect = undefined as any;\n hook.dependencies = undefined;\n });\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = undefined;\n hook.nextValue = undefined;\n hook.setter = undefined as any;\n });\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n hook.dependencies = undefined as any;\n });\n\n componentInstance.hooks = undefined as any;\n componentInstance.$element = undefined as any;\n componentInstance.renderedValue = undefined;\n componentInstance.Component = undefined as any;\n componentInstance.props = undefined as any;\n componentInstance.forceUpdate = undefined;\n componentInstance.onUpdate = undefined;\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 const componentElement = $element.children[0];\n return componentElement ? getTarget(componentElement) : undefined;\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(): [T, StateHookSetter];\nexport function useState(initial: T): [T, StateHookSetter];\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?: readonly 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: any) {\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?: readonly any[], debugKey?: string) {\n return useLayoutEffectBase(fastRaf, fastRafPrimary, effect, dependencies, debugKey);\n}\n\nexport function useLayoutEffect(effect: () => Function | void, dependencies?: readonly 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, debugKey?: string) {\n return function TeactMemoWrapper(props: Props) {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => createElement(Component, props), Object.values(props), debugKey);\n } as T;\n}\n\n// We need to keep it here for JSX.\nconst Teact = {\n createElement,\n Fragment,\n};\n\nexport default Teact;\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 { handleError } from '../../util/handleError';\nimport { isHeavyAnimating } from '../../hooks/useHeavyAnimationCheck';\n\nexport default React;\n\ntype GlobalState = AnyLiteral;\ntype ActionNames = string;\ntype ActionPayload = any;\n\ninterface ActionOptions {\n forceOnHeavyAnimation?: boolean;\n // Workaround for iOS gesture history navigation\n forceSyncOnIOs?: boolean;\n}\n\ntype Actions = Record void>;\n\ntype ActionHandler = (\n global: GlobalState,\n actions: Actions,\n payload: any,\n) => GlobalState | void | Promise;\n\ntype MapStateToProps = ((global: GlobalState, ownProps: OwnProps) => AnyLiteral);\n\nlet currentGlobal = {} as GlobalState;\n\nconst actionHandlers: Record = {};\nconst callbacks: Function[] = [updateContainers];\nconst actions = {} as Actions;\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?: ActionOptions) {\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 getActions() {\n return actions;\n}\n\nfunction handleAction(name: string, payload?: ActionPayload, options?: ActionOptions) {\n actionHandlers[name]?.forEach((handler) => {\n const response = handler(currentGlobal, actions, payload);\n if (!response) {\n return;\n }\n\n if (typeof response.then === 'function') {\n response.then((newGlobal: GlobalState | void) => {\n if (newGlobal) {\n setGlobal(newGlobal, options);\n }\n });\n } else {\n setGlobal(response, options);\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: any) {\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 addActionHandler(name: ActionNames, handler: ActionHandler) {\n if (!actionHandlers[name]) {\n actionHandlers[name] = [];\n\n actions[name] = (payload?: ActionPayload, options?: ActionOptions) => {\n handleAction(name, payload, options);\n };\n }\n\n actionHandlers[name].push(handler);\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: any) {\n handleError(err);\n }\n }\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ;\n };\n };\n}\n\nexport function typify() {\n type NonTypedActionPayloads = {\n [ActionName in NonTypedActionNames]: ActionPayload;\n };\n\n type ProjectActionTypes =\n ActionPayloads\n & NonTypedActionPayloads;\n\n type ProjectActionNames = keyof ProjectActionTypes;\n\n type ProjectActions = {\n [ActionName in ProjectActionNames]: (\n payload?: ProjectActionTypes[ActionName],\n options?: ActionOptions,\n ) => void;\n };\n\n type ActionHandlers = {\n [ActionName in keyof ProjectActionTypes]: (\n global: ProjectGlobalState,\n actions: ProjectActions,\n payload: ProjectActionTypes[ActionName],\n ) => ProjectGlobalState | void | Promise;\n };\n\n return {\n getGlobal: getGlobal as () => ProjectGlobalState,\n setGlobal: setGlobal as (state: ProjectGlobalState, options?: ActionOptions) => void,\n getActions: getActions as () => ProjectActions,\n addActionHandler: addActionHandler as (\n name: ActionName,\n handler: ActionHandlers[ActionName],\n ) => void,\n withGlobal: withGlobal as (\n mapStateToProps: ((global: ProjectGlobalState, ownProps: OwnProps) => AnyLiteral),\n ) => (Component: FC) => FC,\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 ApiBotInlineMediaResult, ApiBotInlineResult, ApiBotInlineSwitchPm,\n ApiChatInviteImporter,\n ApiExportedInvite,\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 isConnectionStatusMinimized: 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 QuickReaction,\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 Search,\n Management,\n Statistics,\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 interface ManagementState {\n isActive: boolean;\n nextScreen?: ManagementScreens;\n isUsernameAvailable?: boolean;\n error?: string;\n invites?: ApiExportedInvite[];\n revokedInvites?: ApiExportedInvite[];\n editingInvite?: ApiExportedInvite;\n inviteInfo?: {\n invite: ApiExportedInvite;\n importers?: ApiChatInviteImporter[];\n requesters?: ApiChatInviteImporter[];\n };\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 ConfirmPayment,\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 ChannelRemovedUsers,\n GroupUserPermissionsCreate,\n GroupUserPermissions,\n ChatAdministrators,\n GroupRecentActions,\n ChatAdminRights,\n ChatNewAdminRights,\n GroupMembers,\n GroupAddAdmins,\n Invites,\n EditInvite,\n Reactions,\n InviteInfo,\n JoinRequests,\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 if (!instance!.isCancelled && tick()) {\n fastRaf(() => {\n animateSingle(tick, instance);\n });\n }\n}\n\nexport function animate(tick: Function) {\n if (tick()) {\n fastRaf(() => {\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)[];\ntype PartsWithGlobals = (string | false | undefined | string[])[];\ntype ClassNameBuilder =\n ((elementName: string, ...modifiers: PartsWithGlobals) => string)\n & Record;\n\nexport default function buildClassName(...parts: Parts) {\n return parts.filter(Boolean).join(' ');\n}\n\nexport function createClassNameBuilder(componentName: string) {\n return ((elementName: string, ...modifiers: PartsWithGlobals) => {\n const baseName = elementName === '&' ? componentName : `${componentName}__${elementName}`;\n\n return modifiers.reduce((acc, modifier) => {\n if (modifier) {\n // A bit hacky way to pass global class names\n if (Array.isArray(modifier)) {\n acc.push(...modifier);\n } else {\n acc.push(`${baseName}--${modifier}`);\n }\n }\n\n return acc;\n }, [baseName]).join(' ');\n }) as ClassNameBuilder;\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 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","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 function hasCallbacks() {\n return Boolean(callbacks.length);\n }\n\n return {\n runCallbacks,\n addCallback,\n removeCallback,\n hasCallbacks,\n };\n}\n\nexport type CallbackManager = ReturnType;\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 { DEBUG } from '../config';\n\nexport const CLIPBOARD_ITEM_SUPPORTED = window.navigator.clipboard && window.ClipboardItem;\n\nconst textCopyEl = document.createElement('textarea');\ntextCopyEl.setAttribute('readonly', '');\ntextCopyEl.tabIndex = -1;\ntextCopyEl.className = 'visually-hidden';\n\nexport const copyTextToClipboard = (str: string): void => {\n textCopyEl.value = str;\n document.body.appendChild(textCopyEl);\n const selection = document.getSelection();\n\n if (selection) {\n // Store previous selection\n const rangeToRestore = selection.rangeCount > 0 && selection.getRangeAt(0);\n textCopyEl.select();\n document.execCommand('copy');\n // Restore the original selection\n if (rangeToRestore) {\n selection.removeAllRanges();\n selection.addRange(rangeToRestore);\n }\n }\n\n document.body.removeChild(textCopyEl);\n};\n\nexport const copyImageToClipboard = (imageUrl?: string) => {\n if (!imageUrl) return;\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n const imageEl = new Image();\n imageEl.onload = (e: Event) => {\n if (ctx && e.currentTarget) {\n const img = e.currentTarget as HTMLImageElement;\n canvas.width = img.width;\n canvas.height = img.height;\n ctx.drawImage(img, 0, 0, img.width, img.height);\n canvas.toBlob(copyBlobToClipboard, 'image/png', 1);\n }\n };\n\n imageEl.src = imageUrl;\n};\n\nasync function copyBlobToClipboard(pngBlob: Blob | null) {\n if (!pngBlob || !CLIPBOARD_ITEM_SUPPORTED) {\n return;\n }\n\n try {\n await window.navigator.clipboard.write?.([\n new ClipboardItem({\n [pngBlob.type]: pngBlob,\n }),\n ]);\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n }\n}\n","import { LangFn } from '../hooks/useLang';\nimport withCache from './withCache';\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 isToday(date: Date) {\n return getDayStartAt(new Date()) === getDayStartAt(date);\n}\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(lang: LangFn, datetime: number | Date) {\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(lang, date);\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 formatCountdown(\n lang: LangFn,\n msLeft: number,\n) {\n const days = Math.floor(msLeft / MILLISECONDS_IN_DAY);\n if (msLeft < 0) {\n return 0;\n } else if (days < 1) {\n return formatMediaDuration(msLeft / 1000);\n } else if (days < 7) {\n return lang('Days', days);\n } else if (days < 30) {\n return lang('Weeks', Math.floor(days / 7));\n } else if (days < 365) {\n return lang('Months', Math.floor(days / 30));\n } else {\n return lang('Years', Math.floor(days / 365));\n }\n}\n\nexport function formatCountdownShort(lang: LangFn, msLeft: number) {\n if (msLeft < 60 * 1000) {\n return Math.ceil(msLeft / 1000);\n } else if (msLeft < 60 * 60 * 1000) {\n return Math.ceil(msLeft / (60 * 1000));\n } else if (msLeft < MILLISECONDS_IN_DAY) {\n return lang('MessageTimer.ShortHours', Math.ceil(msLeft / (60 * 60 * 1000)));\n } else {\n return lang('MessageTimer.ShortDays', Math.ceil(msLeft / MILLISECONDS_IN_DAY));\n }\n}\n\nexport function formatLastUpdated(lang: LangFn, currentTime: number, lastUpdated = currentTime) {\n const seconds = currentTime - lastUpdated;\n if (seconds < 60) {\n return lang('LiveLocationUpdated.JustNow');\n } else if (seconds < 60 * 60) {\n return lang('LiveLocationUpdated.MinutesAgo', Math.floor(seconds / 60));\n } else {\n return lang('LiveLocationUpdated.TodayAt', formatTime(lang, lastUpdated));\n }\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(lang, date)}`;\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\nconst formatDayToStringWithCache = withCache((dayStartAt: number, locale: string) => {\n return new Date(dayStartAt).toLocaleString(\n locale,\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n },\n );\n});\n\nexport function formatDateToString(datetime: Date | number, locale = 'en-US') {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const dayStartAt = getDayStartAt(date);\n\n return formatDayToStringWithCache(dayStartAt, locale);\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 window.navigator.mediaDevices && 'getUserMedia' in window.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');\n// `canPlayType(VIDEO_MOV_TYPE)` returns false negative at least for macOS Chrome and iOS Safari\nexport const IS_MOV_SUPPORTED = true;\n\nif (IS_MOV_SUPPORTED) SUPPORTED_VIDEO_CONTENT_TYPES.add(VIDEO_MOV_TYPE);\n\nexport const IS_WEBM_SUPPORTED = Boolean(TEST_VIDEO.canPlayType('video/webm; codecs=\"vp9\"').replace('no', ''))\n && !(IS_MAC_OS && IS_SAFARI); // Safari on MacOS has some issues with WebM\n\nexport const DPR = window.devicePixelRatio || 1;\n\nexport const MASK_IMAGE_DISABLED = true;\n\nexport const IS_BACKDROP_BLUR_SUPPORTED = !IS_TEST && (\n CSS.supports('backdrop-filter: blur()') || CSS.supports('-webkit-backdrop-filter: blur()')\n);\nexport const IS_COMPACT_MENU = !IS_TOUCH_ENV;\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 { addCallback } from '../lib/teact/teactn';\nimport { addActionHandler, getGlobal } from '../global';\n\nimport { GlobalState } from '../global/types';\nimport { NotifyException, NotifySettings } from '../types';\nimport { ApiChat, ApiChatFolder, ApiUser } from '../api/types';\n\nimport { ALL_FOLDER_ID, ARCHIVED_FOLDER_ID, DEBUG } from '../config';\nimport { selectNotifySettings, selectNotifyExceptions } from '../global/selectors';\nimport { selectIsChatMuted } from '../global/helpers';\nimport { onIdle, throttle } from './schedulers';\nimport { areSortedArraysEqual, unique } from './iteratees';\nimport arePropsShallowEqual from './arePropsShallowEqual';\nimport { CallbackManager, createCallbackManager } from './callbacks';\n\ninterface FolderSummary {\n id: number;\n listIds?: Set;\n orderedPinnedIds?: string[];\n contacts?: true;\n nonContacts?: true;\n groups?: true;\n channels?: true;\n bots?: true;\n excludeMuted?: true;\n excludeRead?: true;\n excludeArchived?: true;\n excludedChatIds?: Set;\n includedChatIds?: Set;\n pinnedChatIds?: Set;\n}\n\ninterface ChatSummary {\n id: string;\n type: ApiChat['type'];\n isListed: boolean;\n isArchived: boolean;\n isMuted: boolean;\n isUnread: boolean;\n unreadCount?: number;\n unreadMentionsCount?: number;\n order: number;\n isUserBot?: boolean;\n isUserContact?: boolean;\n}\n\nconst UPDATE_THROTTLE = 500;\nconst DEBUG_DURATION_LIMIT = 6;\n\nconst initials = buildInitials();\n\nlet prevGlobal: {\n allFolderListIds?: GlobalState['chats']['listIds']['active'];\n allFolderPinnedIds?: GlobalState['chats']['orderedPinnedIds']['active'];\n archivedFolderListIds?: GlobalState['chats']['listIds']['archived'];\n archivedFolderPinnedIds?: GlobalState['chats']['orderedPinnedIds']['archived'];\n isAllFolderFullyLoaded?: boolean;\n isArchivedFolderFullyLoaded?: boolean;\n chatsById: Record;\n foldersById: Record;\n usersById: Record;\n notifySettings: NotifySettings;\n notifyExceptions?: Record;\n} = initials.prevGlobal;\n\nlet prepared: {\n folderSummariesById: Record;\n chatSummariesById: Map;\n folderIdsByChatId: Record;\n chatIdsByFolderId: Record | undefined>;\n isOrderedListJustPatched: Record;\n} = initials.prepared;\n\nlet results: {\n orderedIdsByFolderId: Record;\n pinnedCountByFolderId: Record; // Also watched by `callbacks.orderedIdsByFolderId`\n chatsCountByFolderId: Record;\n unreadCountersByFolderId: Record;\n} = initials.results;\n\nlet callbacks: {\n orderedIdsByFolderId: Record;\n chatsCountByFolderId: CallbackManager;\n unreadCountersByFolderId: CallbackManager;\n} = initials.callbacks;\n\nconst updateFolderManagerThrottled = throttle(() => {\n onIdle(() => {\n updateFolderManager(getGlobal());\n });\n}, UPDATE_THROTTLE);\n\nlet inited = false;\n\n/* Getters */\n\nexport function init() {\n inited = true;\n\n addCallback(updateFolderManagerThrottled);\n addActionHandler('reset', reset);\n\n updateFolderManager(getGlobal());\n}\n\nexport function getOrderedIds(folderId: number) {\n if (!inited) init();\n\n return results.orderedIdsByFolderId[folderId];\n}\n\nexport function getPinnedChatsCount(folderId: number) {\n if (!inited) init();\n\n return results.pinnedCountByFolderId[folderId] || 0;\n}\n\nexport function getChatsCount() {\n if (!inited) init();\n\n return results.chatsCountByFolderId;\n}\n\nexport function getUnreadCounters() {\n if (!inited) init();\n\n return results.unreadCountersByFolderId;\n}\n\nexport function getAllNotificationsCount() {\n return getUnreadCounters()[ALL_FOLDER_ID]?.notificationsCount || 0;\n}\n\n/* Callback managers */\n\nexport function addOrderedIdsCallback(folderId: number, callback: (orderedIds: string[]) => void) {\n if (!callbacks.orderedIdsByFolderId[folderId]) {\n callbacks.orderedIdsByFolderId[folderId] = createCallbackManager();\n }\n\n return callbacks.orderedIdsByFolderId[folderId].addCallback(callback);\n}\n\nexport function addChatsCountCallback(callback: (chatsCount: typeof results.chatsCountByFolderId) => void) {\n return callbacks.chatsCountByFolderId.addCallback(callback);\n}\n\nexport function addUnreadCountersCallback(callback: (unreadCounters: typeof results.unreadCountersByFolderId) => void) {\n return callbacks.unreadCountersByFolderId.addCallback(callback);\n}\n\n/* Global update handlers */\n\nfunction updateFolderManager(global: GlobalState) {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n let DEBUG_startedAt: number;\n if (DEBUG) {\n DEBUG_startedAt = performance.now();\n }\n\n const isAllFolderChanged = Boolean(\n global.chats.listIds.active\n && isMainFolderChanged(ALL_FOLDER_ID, global.chats.listIds.active, global.chats.orderedPinnedIds.active),\n );\n const isArchivedFolderChanged = Boolean(\n global.chats.listIds.archived\n && isMainFolderChanged(ARCHIVED_FOLDER_ID, global.chats.listIds.archived, global.chats.orderedPinnedIds.archived),\n );\n const isAllFullyLoadedChanged = global.chats.isFullyLoaded.active !== prevGlobal.isAllFolderFullyLoaded;\n const isArchivedFullyLoadedChanged = global.chats.isFullyLoaded.archived !== prevGlobal.isArchivedFolderFullyLoaded;\n\n const areFoldersChanged = global.chatFolders.byId !== prevGlobal.foldersById;\n const areChatsChanged = global.chats.byId !== prevGlobal.chatsById;\n const areUsersChanged = global.users.byId !== prevGlobal.usersById;\n const areNotifySettingsChanged = selectNotifySettings(global) !== prevGlobal.notifySettings;\n const areNotifyExceptionsChanged = selectNotifyExceptions(global) !== prevGlobal.notifyExceptions;\n\n let affectedFolderIds: number[] = [];\n\n if (isAllFullyLoadedChanged || isArchivedFullyLoadedChanged) {\n affectedFolderIds = affectedFolderIds.concat(\n updateFullyLoaded(global, isArchivedFullyLoadedChanged),\n );\n }\n\n if (!(\n isAllFolderChanged || isArchivedFolderChanged || areFoldersChanged\n || areChatsChanged || areUsersChanged || areNotifySettingsChanged || areNotifyExceptionsChanged\n )\n ) {\n if (affectedFolderIds.length) {\n updateResults(affectedFolderIds);\n }\n\n return;\n }\n\n const prevAllFolderListIds = prevGlobal.allFolderListIds;\n const prevArchivedFolderListIds = prevGlobal.archivedFolderListIds;\n\n updateFolders(global, isAllFolderChanged, isArchivedFolderChanged, areFoldersChanged);\n\n affectedFolderIds = affectedFolderIds.concat(updateChats(\n global,\n areFoldersChanged || isAllFolderChanged || isArchivedFolderChanged,\n areNotifySettingsChanged,\n areNotifyExceptionsChanged,\n prevAllFolderListIds,\n prevArchivedFolderListIds,\n ));\n\n updateResults(unique(affectedFolderIds));\n\n if (DEBUG) {\n const duration = performance.now() - DEBUG_startedAt!;\n if (duration > DEBUG_DURATION_LIMIT) {\n // eslint-disable-next-line no-console\n console.warn(`Slow \\`updateFolderManager\\`: ${Math.round(duration)} ms`);\n }\n }\n}\n\nfunction isMainFolderChanged(folderId: number, newListIds?: string[], newPinnedIds?: string[]) {\n const currentListIds = folderId === ALL_FOLDER_ID\n ? prevGlobal.allFolderListIds\n : prevGlobal.archivedFolderListIds;\n const currentPinnedIds = folderId === ALL_FOLDER_ID\n ? prevGlobal.allFolderPinnedIds\n : prevGlobal.archivedFolderPinnedIds;\n\n return currentListIds !== newListIds || currentPinnedIds !== newPinnedIds;\n}\n\nfunction updateFullyLoaded(\n global: GlobalState,\n isArchivedFullyLoadedChanged = false,\n) {\n let affectedFolderIds = [];\n\n if (isArchivedFullyLoadedChanged) {\n affectedFolderIds.push(ARCHIVED_FOLDER_ID);\n }\n\n const isAllFolderFullyLoaded = global.chats.isFullyLoaded.active;\n const isArchivedFolderFullyLoaded = global.chats.isFullyLoaded.archived;\n\n if (isAllFolderFullyLoaded && isArchivedFolderFullyLoaded) {\n const emptyFolderIds = Object.keys(prepared.folderSummariesById)\n .filter((folderId) => !results.orderedIdsByFolderId[folderId])\n .map(Number);\n\n affectedFolderIds = affectedFolderIds.concat(emptyFolderIds);\n }\n\n prevGlobal.isAllFolderFullyLoaded = isAllFolderFullyLoaded;\n prevGlobal.isArchivedFolderFullyLoaded = isArchivedFolderFullyLoaded;\n\n return affectedFolderIds;\n}\n\nfunction updateFolders(\n global: GlobalState, isAllFolderChanged: boolean, isArchivedFolderChanged: boolean, areFoldersChanged: boolean,\n) {\n const changedFolders = [];\n\n if (isAllFolderChanged) {\n const newListIds = global.chats.listIds.active!;\n const newPinnedIds = global.chats.orderedPinnedIds.active;\n\n prepared.folderSummariesById[ALL_FOLDER_ID] = buildFolderSummaryFromMainList(\n ALL_FOLDER_ID, newListIds, newPinnedIds,\n );\n\n prevGlobal.allFolderListIds = newListIds;\n prevGlobal.allFolderPinnedIds = newPinnedIds;\n\n changedFolders.push(ALL_FOLDER_ID);\n }\n\n if (isArchivedFolderChanged) {\n const newListIds = global.chats.listIds.archived!;\n const newPinnedIds = global.chats.orderedPinnedIds.archived;\n\n prepared.folderSummariesById[ARCHIVED_FOLDER_ID] = buildFolderSummaryFromMainList(\n ARCHIVED_FOLDER_ID, newListIds, newPinnedIds,\n );\n\n prevGlobal.archivedFolderListIds = newListIds;\n prevGlobal.archivedFolderPinnedIds = newPinnedIds;\n\n changedFolders.push(ARCHIVED_FOLDER_ID);\n }\n\n if (areFoldersChanged) {\n const newFoldersById = global.chatFolders.byId;\n\n Object.values(newFoldersById).forEach((folder) => {\n if (folder === prevGlobal.foldersById[folder.id]) {\n return;\n }\n\n prepared.folderSummariesById[folder.id] = buildFolderSummary(folder);\n\n changedFolders.push(folder.id);\n });\n\n prevGlobal.foldersById = newFoldersById;\n }\n\n return changedFolders;\n}\n\nfunction buildFolderSummaryFromMainList(\n folderId: number, listIds: string[], orderedPinnedIds?: string[],\n): FolderSummary {\n return {\n id: folderId,\n listIds: new Set(listIds),\n orderedPinnedIds,\n pinnedChatIds: new Set(orderedPinnedIds),\n };\n}\n\nfunction buildFolderSummary(folder: ApiChatFolder): FolderSummary {\n return {\n ...folder,\n orderedPinnedIds: folder.pinnedChatIds,\n excludedChatIds: folder.excludedChatIds ? new Set(folder.excludedChatIds) : undefined,\n includedChatIds: folder.excludedChatIds ? new Set(folder.includedChatIds) : undefined,\n pinnedChatIds: folder.excludedChatIds ? new Set(folder.pinnedChatIds) : undefined,\n };\n}\n\nfunction updateChats(\n global: GlobalState,\n areFoldersChanged: boolean,\n areNotifySettingsChanged: boolean,\n areNotifyExceptionsChanged: boolean,\n prevAllFolderListIds?: string[],\n prevArchivedFolderListIds?: string[],\n) {\n const newChatsById = global.chats.byId;\n const newUsersById = global.users.byId;\n const newNotifySettings = selectNotifySettings(global);\n const newNotifyExceptions = selectNotifyExceptions(global);\n const folderSummaries = Object.values(prepared.folderSummariesById);\n const affectedFolderIds = new Set();\n\n const newAllFolderListIds = global.chats.listIds.active;\n const newArchivedFolderListIds = global.chats.listIds.archived;\n let allIds = [...newAllFolderListIds || [], ...newArchivedFolderListIds || []];\n if (newAllFolderListIds !== prevAllFolderListIds || newArchivedFolderListIds !== prevArchivedFolderListIds) {\n allIds = unique(allIds.concat(prevAllFolderListIds || [], prevArchivedFolderListIds || []));\n }\n\n allIds.forEach((chatId) => {\n const chat = newChatsById[chatId];\n\n if (\n !areFoldersChanged\n && !areNotifySettingsChanged\n && !areNotifyExceptionsChanged\n && chat === prevGlobal.chatsById[chatId]\n && newUsersById[chatId] === prevGlobal.usersById[chatId]\n ) {\n return;\n }\n\n let newFolderIds: number[];\n if (chat) {\n const currentSummary = prepared.chatSummariesById.get(chatId);\n const newSummary = buildChatSummary(chat, newNotifySettings, newNotifyExceptions, newUsersById[chatId]);\n if (!areFoldersChanged && currentSummary && arePropsShallowEqual(newSummary, currentSummary)) {\n return;\n }\n\n prepared.chatSummariesById.set(chatId, newSummary);\n\n newFolderIds = buildChatFolderIds(newSummary, folderSummaries);\n newFolderIds.forEach((folderId) => {\n affectedFolderIds.add(folderId);\n });\n } else {\n prepared.chatSummariesById.delete(chatId);\n newFolderIds = [];\n }\n\n const currentFolderIds = prepared.folderIdsByChatId[chatId] || [];\n if (areSortedArraysEqual(newFolderIds, currentFolderIds)) {\n return;\n }\n\n const deletedFolderIds = updateListsForChat(chatId, currentFolderIds, newFolderIds);\n deletedFolderIds.forEach((folderId) => {\n affectedFolderIds.add(folderId);\n });\n });\n\n prevGlobal.chatsById = newChatsById;\n prevGlobal.usersById = newUsersById;\n prevGlobal.notifySettings = newNotifySettings;\n prevGlobal.notifyExceptions = newNotifyExceptions;\n\n return Array.from(affectedFolderIds);\n}\n\nfunction buildChatSummary(\n chat: ApiChat,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n user?: ApiUser,\n): ChatSummary {\n const {\n id, type, lastMessage, isRestricted, isNotJoined, folderId,\n unreadCount, unreadMentionsCount, hasUnreadMark,\n joinDate, draftDate,\n } = chat;\n\n const userInfo = type === 'chatTypePrivate' && user;\n\n return {\n id,\n type,\n isListed: Boolean(lastMessage && !isRestricted && !isNotJoined),\n isArchived: folderId === ARCHIVED_FOLDER_ID,\n isMuted: selectIsChatMuted(chat, notifySettings, notifyExceptions),\n isUnread: Boolean(unreadCount || unreadMentionsCount || hasUnreadMark),\n unreadCount,\n unreadMentionsCount,\n order: Math.max(joinDate || 0, draftDate || 0, lastMessage?.date || 0),\n isUserBot: userInfo ? userInfo.type === 'userTypeBot' : undefined,\n isUserContact: userInfo ? userInfo.isContact : undefined,\n };\n}\n\nfunction buildChatFolderIds(chatSummary: ChatSummary, folderSummaries: FolderSummary[]) {\n return folderSummaries.reduce((acc, folderSummary) => {\n if (isChatInFolder(chatSummary, folderSummary)) {\n acc.push(folderSummary.id);\n }\n\n return acc;\n }, []).sort();\n}\n\nfunction isChatInFolder(\n chatSummary: ChatSummary,\n folderSummary: FolderSummary,\n) {\n if (!chatSummary.isListed) {\n return false;\n }\n\n const { id: chatId, type } = chatSummary;\n\n if (folderSummary.listIds) {\n if (\n (chatSummary.isArchived && folderSummary.id === ALL_FOLDER_ID)\n || (!chatSummary.isArchived && folderSummary.id === ARCHIVED_FOLDER_ID)\n ) {\n return false;\n }\n\n return folderSummary.listIds.has(chatId);\n }\n\n if (folderSummary.excludedChatIds?.has(chatId)) {\n return false;\n }\n\n if (folderSummary.includedChatIds?.has(chatId)) {\n return true;\n }\n\n if (folderSummary.pinnedChatIds?.has(chatId)) {\n return true;\n }\n\n if (folderSummary.excludeArchived && chatSummary.isArchived) {\n return false;\n }\n\n if (folderSummary.excludeRead && !chatSummary.isUnread) {\n return false;\n }\n\n if (folderSummary.excludeMuted && chatSummary.isMuted && !chatSummary.unreadMentionsCount) {\n return false;\n }\n\n if (type === 'chatTypePrivate') {\n if (chatSummary.isUserBot) {\n if (folderSummary.bots) {\n return true;\n }\n } else {\n if (folderSummary.contacts && chatSummary.isUserContact) {\n return true;\n }\n\n if (folderSummary.nonContacts && !chatSummary.isUserContact) {\n return true;\n }\n }\n } else if (type === 'chatTypeChannel') {\n return Boolean(folderSummary.channels);\n } else if (type === 'chatTypeBasicGroup' || type === 'chatTypeSuperGroup') {\n return Boolean(folderSummary.groups);\n }\n\n return false;\n}\n\nfunction updateListsForChat(chatId: string, currentFolderIds: number[], newFolderIds: number[]) {\n const currentFolderIdsSet = new Set(currentFolderIds);\n const newFolderIdsSet = new Set(newFolderIds);\n const deletedFolderIds: number[] = [];\n\n unique([...currentFolderIds, ...newFolderIds]).forEach((folderId) => {\n let currentFolderOrderedIds = results.orderedIdsByFolderId[folderId];\n\n if (currentFolderIdsSet.has(folderId) && !newFolderIdsSet.has(folderId)) {\n prepared.chatIdsByFolderId[folderId]!.delete(chatId);\n\n deletedFolderIds.push(folderId);\n\n if (currentFolderOrderedIds) {\n currentFolderOrderedIds = currentFolderOrderedIds.filter((id) => id !== chatId);\n prepared.isOrderedListJustPatched[folderId] = true;\n }\n } else if (!currentFolderIdsSet.has(folderId) && newFolderIdsSet.has(folderId)) {\n if (!prepared.chatIdsByFolderId[folderId]) {\n prepared.chatIdsByFolderId[folderId] = new Set();\n }\n\n prepared.chatIdsByFolderId[folderId]!.add(chatId);\n\n if (currentFolderOrderedIds) {\n currentFolderOrderedIds.push(chatId);\n prepared.isOrderedListJustPatched[folderId] = true;\n }\n }\n\n results.orderedIdsByFolderId[folderId] = currentFolderOrderedIds;\n });\n\n prepared.folderIdsByChatId[chatId] = newFolderIds;\n\n return deletedFolderIds;\n}\n\nfunction updateResults(affectedFolderIds: number[]) {\n let wasUnreadCountersChanged = false;\n let wasChatsCountChanged = false;\n\n Array.from(affectedFolderIds).forEach((folderId) => {\n const { pinnedCount: newPinnedCount, orderedIds: newOrderedIds } = buildFolderOrderedIds(folderId);\n // When signed out\n if (!newOrderedIds) {\n return;\n }\n\n const currentOrderedIds = results.orderedIdsByFolderId[folderId];\n const currentPinnedCount = results.pinnedCountByFolderId[folderId];\n const areOrderedIdsChanged = (\n !currentOrderedIds\n || currentPinnedCount === undefined || currentPinnedCount !== newPinnedCount\n || prepared.isOrderedListJustPatched[folderId]\n || !areSortedArraysEqual(newOrderedIds, currentOrderedIds)\n );\n if (areOrderedIdsChanged) {\n prepared.isOrderedListJustPatched[folderId] = false;\n results.orderedIdsByFolderId[folderId] = newOrderedIds;\n results.pinnedCountByFolderId[folderId] = newPinnedCount;\n callbacks.orderedIdsByFolderId[folderId]?.runCallbacks(newOrderedIds);\n }\n\n const currentChatsCount = results.chatsCountByFolderId[folderId];\n const newChatsCount = newOrderedIds.length;\n if (!wasChatsCountChanged) {\n wasChatsCountChanged = currentChatsCount !== newChatsCount;\n }\n results.chatsCountByFolderId[folderId] = newChatsCount;\n\n const currentUnreadCounters = results.unreadCountersByFolderId[folderId];\n const newUnreadCounters = buildFolderUnreadCounters(folderId);\n if (!wasUnreadCountersChanged) {\n wasUnreadCountersChanged = (\n !currentUnreadCounters || !arePropsShallowEqual(newUnreadCounters, currentUnreadCounters)\n );\n }\n results.unreadCountersByFolderId[folderId] = newUnreadCounters;\n });\n\n if (wasChatsCountChanged) {\n // We need to update the entire object as it will be returned from a hook\n const newValue = { ...results.chatsCountByFolderId };\n results.chatsCountByFolderId = newValue;\n callbacks.chatsCountByFolderId.runCallbacks(newValue);\n }\n\n if (wasUnreadCountersChanged) {\n // We need to update the entire object as it will be returned from a hook\n const newValue = { ...results.unreadCountersByFolderId };\n results.unreadCountersByFolderId = newValue;\n callbacks.unreadCountersByFolderId.runCallbacks(newValue);\n }\n}\n\nfunction buildFolderOrderedIds(folderId: number) {\n const folderSummary = prepared.folderSummariesById[folderId];\n if (!folderSummary) {\n return {};\n }\n\n const { orderedPinnedIds, pinnedChatIds } = folderSummary;\n const {\n chatSummariesById,\n chatIdsByFolderId: { [folderId]: chatIds },\n } = prepared;\n const {\n orderedIdsByFolderId: { [folderId]: prevOrderedIds },\n } = results;\n\n const sortedPinnedIds = chatIds ? orderedPinnedIds?.filter((id) => chatIds.has(id)) : orderedPinnedIds;\n const allListIds = prevOrderedIds || (chatIds && Array.from(chatIds)) || [];\n const notPinnedIds = pinnedChatIds ? allListIds.filter((id) => !pinnedChatIds.has(id)) : allListIds;\n const sortedNotPinnedIds = notPinnedIds.sort((chatId1: string, chatId2: string) => {\n return chatSummariesById.get(chatId2)!.order - chatSummariesById.get(chatId1)!.order;\n });\n\n return {\n pinnedCount: sortedPinnedIds?.length || 0,\n orderedIds: [\n ...(sortedPinnedIds || []),\n ...sortedNotPinnedIds,\n ],\n };\n}\n\nfunction buildFolderUnreadCounters(folderId: number) {\n const {\n chatSummariesById,\n } = prepared;\n const {\n orderedIdsByFolderId: { [folderId]: orderedIds },\n } = results;\n\n return orderedIds!.reduce((newUnreadCounters, chatId) => {\n const chatSummary = chatSummariesById.get(chatId);\n if (!chatSummary) {\n return newUnreadCounters;\n }\n\n if (chatSummary.isUnread) {\n newUnreadCounters.chatsCount++;\n\n if (chatSummary.unreadMentionsCount) {\n newUnreadCounters.notificationsCount += chatSummary.unreadMentionsCount;\n }\n\n if (!chatSummary.isMuted) {\n if (chatSummary.unreadCount) {\n newUnreadCounters.notificationsCount += chatSummary.unreadCount;\n } else if (!chatSummary.unreadMentionsCount) {\n newUnreadCounters.notificationsCount += 1; // Manually marked unread\n }\n }\n }\n\n return newUnreadCounters;\n }, {\n chatsCount: 0,\n notificationsCount: 0,\n });\n}\n\nfunction buildInitials() {\n return {\n prevGlobal: {\n foldersById: {},\n chatsById: {},\n usersById: {},\n notifySettings: {} as NotifySettings,\n notifyExceptions: {},\n },\n\n prepared: {\n folderSummariesById: {},\n chatSummariesById: new Map(),\n folderIdsByChatId: {},\n chatIdsByFolderId: {},\n isOrderedListJustPatched: {},\n },\n\n results: {\n orderedIdsByFolderId: {},\n pinnedCountByFolderId: {},\n chatsCountByFolderId: {},\n unreadCountersByFolderId: {},\n },\n\n callbacks: {\n orderedIdsByFolderId: {},\n chatsCountByFolderId: createCallbackManager(),\n unreadCountersByFolderId: createCallbackManager(),\n },\n };\n}\n\nfunction reset() {\n const newInitials = buildInitials();\n\n prevGlobal = newInitials.prevGlobal;\n prepared = newInitials.prepared;\n results = newInitials.results;\n callbacks = newInitials.callbacks;\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","const generateIdFor = (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\nexport default generateIdFor;\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 // eslint-disable-next-line max-len\n SERVICE_WORKER_DISABLED: 'Service Worker is disabled. Streaming media may not be supported. Try reloading 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 BOT_PRECHECKOUT_TIMEOUT: 'The request for payment has expired',\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 // https://stackoverflow.com/questions/49384120/resizeobserver-loop-limit-exceeded\n if (e instanceof ErrorEvent && e.message === 'ResizeObserver loop limit exceeded') {\n return;\n }\n\n e.preventDefault();\n\n handleError(e instanceof ErrorEvent ? (e.error || e.message) : 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: T[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(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 '../global';\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","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 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.Blob,\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 ApiPreparedMedia;\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: Exclude): 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';\nimport { createCallbackManager } from './callbacks';\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\nconst { addCallback, runCallbacks } = createCallbackManager();\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(runCallbacks);\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\nexport const addLoadListener = addCallback;\n","import { callApi } from '../api/gramjs';\nimport {\n ApiChat, ApiMediaFormat, ApiMessage, ApiUser, ApiUserReaction,\n} from '../api/types';\nimport { renderActionMessageText } from '../components/common/helpers/renderActionMessageText';\nimport { DEBUG, IS_TEST } from '../config';\nimport { getActions, getGlobal, setGlobal } from '../global';\nimport {\n getChatAvatarHash,\n getChatTitle,\n getMessageAction,\n getMessageRecentReaction,\n getMessageSenderName,\n getMessageSummaryText,\n getPrivateChatUserId,\n isActionMessage,\n isChatChannel,\n selectIsChatMuted,\n selectShouldShowMessagePreview,\n} from '../global/helpers';\nimport { addNotifyExceptions, replaceSettings } from '../global/reducers';\nimport {\n selectChatMessage,\n selectCurrentMessageList,\n selectNotifyExceptions,\n selectNotifySettings,\n selectUser,\n} from '../global/selectors';\nimport { IS_SERVICE_WORKER_SUPPORTED, IS_TOUCH_ENV } from './environment';\nimport { getTranslation } from './langProvider';\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 = getActions();\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 getActions()\n .setDeviceToken(deviceToken);\n } catch (error: any) {\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 // On touch devices show notifications when chat is not active\n if (IS_TOUCH_ENV) {\n const {\n chatId,\n type,\n } = selectCurrentMessageList(global) || {};\n return !(chatId === chat.id && type === 'thread');\n }\n // On desktop show notifications when window is not focused\n return !document.hasFocus();\n}\n\nfunction getNotificationContent(chat: ApiChat, message: ApiMessage, reaction?: ApiUserReaction) {\n const global = getGlobal();\n const {\n replyToMessageId,\n } = message;\n let {\n senderId,\n } = message;\n if (reaction) senderId = reaction.userId;\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 isChat = chat && (isChatChannel(chat) || message.senderId === message.chatId);\n\n body = renderActionMessageText(\n getTranslation,\n message,\n !isChat ? messageSender : undefined,\n isChat ? chat : undefined,\n actionTargetUsers,\n actionTargetMessage,\n actionTargetChatId,\n { asPlainText: true },\n ) as string;\n } else {\n const senderName = getMessageSenderName(getTranslation, chat.id, messageSender);\n const summary = getMessageSummaryText(getTranslation, message, false, 60, false);\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 notifyAboutMessage({\n chat,\n message,\n isReaction = false,\n}: { chat: ApiChat; message: Partial; isReaction?: boolean }) {\n const { hasWebNotifications } = await loadNotificationSettings();\n if (!checkIfShouldNotify(chat)) return;\n const areNotificationsSupported = checkIfNotificationsSupported();\n if (!hasWebNotifications || !areNotificationsSupported) {\n // Do not play notification sound for reactions if web notifications are disabled\n if (isReaction) return;\n // Only play sound if web notifications are disabled\n playNotifySoundDebounced(String(message.id) || chat.id);\n return;\n }\n if (!areNotificationsSupported) return;\n\n if (!message.id) return;\n\n const activeReaction = getMessageRecentReaction(message);\n const icon = await getAvatar(chat);\n\n const {\n title,\n body,\n } = getNotificationContent(chat, message as ApiMessage, activeReaction);\n\n if (checkIfPushSupported()) {\n if (navigator.serviceWorker?.controller) {\n // notify service worker about new message notification\n navigator.serviceWorker.controller.postMessage({\n type: 'showMessageNotification',\n payload: {\n title,\n body,\n icon,\n chatId: chat.id,\n messageId: message.id,\n reaction: activeReaction?.reaction,\n },\n });\n }\n } else {\n const dispatch = getActions();\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 (activeReaction) {\n dispatch.startActiveReaction({\n messageId: message.id,\n reaction: activeReaction.reaction,\n });\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\nimport { LOCATION_HASH } from '../hooks/useHistoryBack';\n\nexport function createMessageHash(messageList: MessageList) {\n const typeOrThreadId = messageList.type !== 'thread' ? (\n `_${messageList.type}`\n ) : messageList.threadId !== -1 ? (\n `_${messageList.threadId}`\n ) : '';\n\n return `${messageList.chatId}${typeOrThreadId}`;\n}\n\nexport function parseLocationHash() {\n if (!LOCATION_HASH) return undefined;\n\n const [chatId, typeOrThreadId] = LOCATION_HASH.replace(/^#/, '').split('_');\n if (!chatId?.match(/^-?\\d+$/)) return undefined;\n\n const isType = ['thread', 'pinned', 'scheduled'].includes(typeOrThreadId);\n\n return {\n chatId,\n type: Boolean(typeOrThreadId) && isType ? (typeOrThreadId as MessageListType) : 'thread',\n threadId: Boolean(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 = /[^\\p{L}\\p{M}]+/ui;\n} catch (e) {\n // Support for older versions of firefox\n RE_NOT_LETTER = /[^\\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 * Delete multiple keys at once.\n *\n * @param keys List of keys to delete.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction delMany(keys, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n keys.forEach((key) => 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(store, callback) {\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 * 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 return customStore('readonly', (store) => {\n // Fast path for modern browsers\n if (store.getAllKeys) {\n return promisifyRequest(store.getAllKeys());\n }\n const items = [];\n return eachCursor(store, (cursor) => items.push(cursor.key)).then(() => items);\n });\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 return customStore('readonly', (store) => {\n // Fast path for modern browsers\n if (store.getAll) {\n return promisifyRequest(store.getAll());\n }\n const items = [];\n return eachCursor(store, (cursor) => items.push(cursor.value)).then(() => items);\n });\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 return customStore('readonly', (store) => {\n // Fast path for modern browsers\n // (although, hopefully we'll get a simpler path some day)\n if (store.getAll && store.getAllKeys) {\n return Promise.all([\n promisifyRequest(store.getAllKeys()),\n promisifyRequest(store.getAll()),\n ]).then(([keys, values]) => keys.map((key, i) => [key, values[i]]));\n }\n const items = [];\n return customStore('readonly', (store) => eachCursor(store, (cursor) => items.push([cursor.key, cursor.value])).then(() => items));\n });\n}\n\nexport { clear, createStore, del, delMany, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","/**\n * Work around Safari 14 IndexedDB open bug.\n *\n * Safari has a horrible bug where IDB requests can hang while the browser is starting up. https://bugs.webkit.org/show_bug.cgi?id=226547\n * The only solution is to keep nudging it until it's awake.\n */\nfunction idbReady() {\n var 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 var intervalId;\n return new Promise(function (resolve) {\n var tryIdb = function () { return indexedDB.databases().finally(resolve); };\n intervalId = setInterval(tryIdb, 100);\n tryIdb();\n }).finally(function () { return 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';\nimport { fastRaf } from './schedulers';\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\nconst switchTheme = (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 fastRaf(() => {\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 });\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\nexport default switchTheme;\n","import EMOJI_REGEX from '../lib/twemojiRegex';\nimport { fixNonStandardEmoji } from './emoji';\nimport withCache from './withCache';\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 const getFirstLetters = withCache((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","export default function trimText(text: T, length?: number) {\n if (!text || !length || text.length <= length) {\n return text;\n }\n\n return `${text.substring(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 '../global';\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 = () => Boolean(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\nexport function clearWebsync() {\n localStorage.removeItem(WEBSYNC_KEY);\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 currentWindowSize = updateSizes();\nlet isRefreshDisabled = false;\n\nfunction disableRefresh() {\n isRefreshDisabled = true;\n}\n\nfunction enableRefresh() {\n isRefreshDisabled = false;\n}\n\nconst handleResize = throttle(() => {\n currentWindowSize = 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 currentWindowSize.width <= MOBILE_SCREEN_MAX_WIDTH || (\n currentWindowSize.width <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH\n && currentWindowSize.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\nconst windowSize = {\n get: () => currentWindowSize,\n getIsKeyboardVisible: () => initialHeight > currentWindowSize.height,\n disableRefresh,\n enableRefresh,\n};\n\nexport default windowSize;\n","const cache = new WeakMap>();\n\nexport default function withCache(fn: T) {\n return (...args: Parameters): ReturnType => {\n let fnCache = cache.get(fn);\n const cacheKey = args.map(String).join('_');\n\n if (fnCache) {\n const cached = fnCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n } else {\n fnCache = new Map();\n cache.set(fn, fnCache);\n }\n\n const newValue = fn(...args);\n\n fnCache.set(cacheKey, newValue);\n\n return newValue;\n };\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 + \".\" + {\"13\":\"1cb726dfb0fe77ff16db\",\"99\":\"a19f6cfb125132c4ae9e\",\"133\":\"e050778acd78ac17365a\",\"161\":\"e3dd8735bd9f827bebc6\",\"354\":\"71017c16320a06ddc8da\",\"395\":\"368d08862d9c65a1cf98\",\"472\":\"38e2fa9338b8e031169b\",\"501\":\"17afb8957510497ebb61\",\"524\":\"e3a446e0b4e9c7ce5ef9\",\"536\":\"51c4121ec6034fff4884\",\"616\":\"dfb0d60d06da102bbad4\",\"654\":\"229871d7a07987919e6c\",\"742\":\"e09d8d2bec0ce4cf0543\",\"745\":\"7f9b9b63ef7b71c5b2d7\",\"878\":\"ba2ac4194b79d543b70f\",\"888\":\"3bcf93fb3c92294b2737\",\"915\":\"7c6d5a7308348c57bbbd\",\"941\":\"1399f916762c873a48a2\",\"970\":\"81d005f8fdd6b7e03eb7\",\"993\":\"c7c8681e7135da951723\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"\" + chunkId + \".\" + {\"13\":\"1cb726dfb0fe77ff16db\",\"133\":\"e050778acd78ac17365a\",\"395\":\"368d08862d9c65a1cf98\",\"472\":\"38e2fa9338b8e031169b\",\"616\":\"dfb0d60d06da102bbad4\",\"654\":\"229871d7a07987919e6c\",\"878\":\"ba2ac4194b79d543b70f\"}[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[chunkId] = 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 { getActions } from '../global';\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 = getActions();\n const payload = action.payload;\n switch (action.type) {\n case 'focusMessage':\n if (dispatch.focusMessage) {\n dispatch.focusMessage(payload);\n }\n if (dispatch.startActiveReaction && payload.reaction) {\n dispatch.startActiveReaction({\n messageId: payload.messageId,\n reaction: payload.reaction,\n });\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 if (!navigator.serviceWorker.controller) {\n const registrations = await navigator.serviceWorker.getRegistrations();\n if (registrations.length) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] Hard reload detected, re-enabling Service Worker');\n }\n await Promise.all(registrations.map((r) => r.unregister()));\n }\n }\n\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 getActions().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 volume: DEFAULT_VOLUME,\n playbackRate: DEFAULT_PLAYBACK_RATE,\n isMuted: false,\n },\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 isConnectionStatusMinimized: true,\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 activeReactions: {},\n\n shouldShowContextMenuHint: true,\n\n activeDownloads: {\n byChatId: {},\n },\n\n serviceNotifications: [],\n\n statistics: {\n byChatId: {},\n },\n};\n","import { addCallback, removeCallback } from '../lib/teact/teactn';\n\nimport { addActionHandler, getGlobal } from './index';\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_USER_LIST_LIMIT,\n GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT,\n GLOBAL_STATE_CACHE_CHATS_WITH_MESSAGES_LIMIT,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n DEFAULT_VOLUME,\n DEFAULT_PLAYBACK_RATE,\n ALL_FOLDER_ID,\n ARCHIVED_FOLDER_ID,\n} from '../config';\nimport { IS_SINGLE_COLUMN_LAYOUT } from '../util/environment';\nimport { isHeavyAnimating } from '../hooks/useHeavyAnimationCheck';\nimport { pick, unique } from '../util/iteratees';\nimport {\n selectCurrentChat,\n selectCurrentMessageList,\n selectVisibleUsers,\n} from './selectors';\nimport { hasStoredSession } from '../util/sessions';\nimport { INITIAL_STATE } from './initialState';\nimport { parseLocationHash } from '../util/routing';\nimport { isUserId } from './helpers';\nimport { getOrderedIds } from '../util/folderManager';\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 addActionHandler('saveSession', () => {\n if (isCaching) {\n return;\n }\n\n setupCaching();\n });\n\n addActionHandler('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() : 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 // Migrate from legacy setting names\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 // Pre-fill settings with defaults\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.mediaViewer.volume === undefined) {\n cached.mediaViewer.volume = DEFAULT_VOLUME;\n }\n\n if (cached.mediaViewer.playbackRate === undefined) {\n cached.mediaViewer.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 if (!cached.activeReactions) {\n cached.activeReactions = {};\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 mediaViewer: {\n volume: global.mediaViewer.volume,\n playbackRate: global.mediaViewer.playbackRate,\n isMuted: global.mediaViewer.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 availableReactions: reduceAvailableReactions(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 }, currentUserId } = global;\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const visibleUserIds = selectVisibleUsers(global)?.map(({ id }) => id);\n\n const idsToSave = unique([\n ...currentUserId ? [currentUserId] : [],\n ...currentChatId && isUserId(currentChatId) ? [currentChatId] : [],\n ...visibleUserIds || [],\n ...global.topPeers.userIds || [],\n ...getOrderedIds(ALL_FOLDER_ID)?.filter(isUserId) || [],\n ...getOrderedIds(ARCHIVED_FOLDER_ID)?.filter(isUserId) || [],\n ...global.contactList?.userIds || [],\n ...global.globalSearch.recentlyFoundChatIds?.filter(isUserId) || [],\n ...Object.keys(byId),\n ]).slice(0, GLOBAL_STATE_CACHE_USER_LIST_LIMIT);\n\n return {\n byId: pick(byId, idsToSave),\n statusesById: pick(statusesById, idsToSave),\n };\n}\n\nfunction reduceChats(global: GlobalState): GlobalState['chats'] {\n const { chats: { byId }, currentUserId } = global;\n const currentChat = selectCurrentChat(global);\n const idsToSave = unique([\n ...currentUserId ? [currentUserId] : [],\n ...currentChat ? [currentChat.id] : [],\n ...getOrderedIds(ALL_FOLDER_ID) || [],\n ...getOrderedIds(ARCHIVED_FOLDER_ID) || [],\n ...global.globalSearch.recentlyFoundChatIds || [],\n ...Object.keys(byId),\n ]).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT);\n\n return {\n ...global.chats,\n isFullyLoaded: {},\n byId: pick(global.chats.byId, idsToSave),\n };\n}\n\nfunction reduceMessages(global: GlobalState): GlobalState['messages'] {\n const { currentUserId } = global;\n const byChatId: GlobalState['messages']['byChatId'] = {};\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const chatIdsToSave = [\n ...currentChatId ? [currentChatId] : [],\n ...currentUserId ? [currentUserId] : [],\n ...getOrderedIds(ALL_FOLDER_ID)?.slice(0, GLOBAL_STATE_CACHE_CHATS_WITH_MESSAGES_LIMIT) || [],\n ];\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\nfunction reduceAvailableReactions(global: GlobalState): GlobalState['availableReactions'] {\n return global.availableReactions\n ?.map((r) => pick(r, ['reaction', 'staticIcon', 'title', 'isInactive']));\n}\n","import { addActionHandler } from './index';\n\nimport { INITIAL_STATE } from './initialState';\nimport { initCache, loadCache } from './cache';\nimport { cloneDeep } from '../util/iteratees';\n\ninitCache();\n\naddActionHandler('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 { getActions, getGlobal, withGlobal } from '../../global';\n\nimport { ApiMediaFormat } from '../../api/types';\nimport { GlobalState } from '../../global/types';\n\nimport { getChatAvatarHash } from '../../global/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\nimport telegramLogoPath from '../../assets/telegram-logo.svg';\nimport reactionThumbsPath from '../../assets/reaction-thumbs.png';\nimport monkeyPath from '../../assets/monkey.svg';\nimport { selectIsRightColumnShown, selectTheme } from '../../global/selectors';\n\ntype OwnProps = {\n page: 'main' | 'authCode' | 'authPassword' | 'authPhoneNumber' | 'authQrCode';\n children: React.ReactNode;\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 preloadImage(reactionThumbsPath),\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 } = getActions();\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\nconst useLangString = (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\nexport default useLangString;\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 '../../global';\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 }> = useCallback(({ 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 }, [filter, handleInput, handleInputKeyDown, id, isLoading, lang, value]);\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\nimport monkeyPath from '../../assets/monkey.svg';\n\nimport React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../global';\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 } = getActions();\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 } = getActions();\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.QR2.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 { getActions, withGlobal } from '../../global';\n\nimport { GlobalState } from '../../global/types';\n\nimport '../../global/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 } = getActions();\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 React, { FC, useEffect } from './lib/teact/teact';\nimport { getActions, withGlobal } from './global';\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 } = getActions();\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 from './lib/teact/teact';\nimport TeactDOM from './lib/teact/teact-dom';\n\nimport { getActions, getGlobal } from './global';\nimport './global/init';\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\ngetActions().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","ensureWorkerPing","setTimeout","makeRequest","args","callApi","fnName","warn","promise","name","err","cancelApiProgress","progressCallback","isCanceled","postMessage","generateIdFor","payload","Promise","Object","assign","pop","set","catch","finally","delete","startedAt","Date","now","async","race","pause","then","location","reload","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","getActions","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","openChat","id","Link","focusMessage","handleMessageClick","chatId","groupCall","joinGroupCall","accessHash","MAX_LENGTH","NBSP","renderActionMessageText","lang","actionOriginUser","actionOriginChat","targetUsers","targetMessage","targetChatId","options","action","translationValues","amount","currency","call","noLinks","asPlainText","asTextWithSpoilers","translationKey","processed","unprocessed","undefined","includes","processPlaceholder","formatCurrency","code","renderUserContent","renderChatContent","map","user","filter","renderMessageContent","renderProductContent","renderMigratedContent","trim","renderGroupCallContent","invoice","getMessageSummaryText","messageSummary","renderMessageSummary","trimText","getUserFullName","renderText","chat","getChatTitle","placeholder","replaceValue","placeholderPosition","substring","Array","isArray","forEach","index","renderMessageText","highlight","shouldRenderHqEmoji","isSimple","truncateLength","entities","contentNotSupportedText","getMessageText","renderTextWithEntities","noEmoji","TRUNCATED_SUMMARY_LENGTH","hasSpoilers","some","emoji","getMessageSummaryEmoji","emojiWithSpace","description","getMessageSummaryDescription","RE_LETTER_OR_DIGIT","SIMPLE_MARKDOWN_REGEX","part","filters","params","compact","reduce","escapeHtml","EMOJI_REGEX","replaceEmojis","addLineBreaks","addHighlight","addLinks","replaceSimpleMarkdown","textParts","divEl","createElement","result","innerText","innerHTML","size","IS_EMOJI_SUPPORTED","parts","fixNonStandardEmoji","emojis","emojiResult","nativeToUnified","removeVS16s","src","alt","splittenParts","line","source","trimmedLine","trimLeft","indentLength","repeat","lowerCaseText","toLowerCase","queryPosition","nextSymbol","newParts","RE_LINK","RE_LINK_TEMPLATE","RE_MENTION_TEMPLATE","links","nextLink","shift","lastIndex","startsWith","username","endsWith","entityResult","entity","actionsByMessageId","createClassNameBuilder","contentRef","useRef","isRevealed","reveal","conceal","useFlag","stopPropagation","actions","contentLength","current","readingMs","round","timeoutMs","max","min","useEffect","has","ref","shouldRenderAsHtml","renderMessagePart","deleteLineBreakAfterPre","organizedEntities","organizedEntityIndexes","Set","organizedEntity","organizeEntity","organizedIndexes","organizedIndex","add","organizeEntities","renderEntity","textPartStart","textPartEnd","isLastEntity","renderResult","nestedEntities","offset","textBefore","textBeforeLength","substr","entityStartIndex","entityEndIndex","entityContent","nestedEntityContent","nestedIndex","nestedEntity","nestedEntityIndex","nestedResult","nestedEntityEndIndex","newEntity","rawEntityText","renderedContent","userId","getLinkUrl","processEntityAsHtml","entityText","renderNestedMessagePart","handleBotCommandClick","handleHashtagClick","handleCodeClick","role","tabIndex","MentionLink","SafeLink","processEntity","textAfter","arrayIndex","getTextWithEntitiesAsHtml","formattedText","c","concat","parsedEntity","isChanged","sendBotCommand","command","currentTarget","setLocalTextSearchQuery","query","searchTextMessagesLocal","copyTextToClipboard","showNotification","getTranslation","preventMessageInputBlur","withBubbling","IS_IOS","activeElement","EDITABLE_INPUT_ID","preventMessageInputBlurWithBubbling","withGlobal","global","userOrChat","selectUser","openChatByUsername","onContextMenu","onMouseDown","onMouseEnter","onMouseLeave","onFocus","color","backgroundImage","pill","fluid","isText","isLoading","ariaLabel","ariaControls","hasPopup","download","disabled","ripple","faded","withClickPropagation","elementRef","isClicked","setIsClicked","useState","fullClassName","handleMouseDown","style","label","subLabel","checked","blocking","onChange","onCheck","useLang","handleChange","event","trigger","positionX","positionY","footer","forceOpen","onOpen","onClose","menuRef","dropdownRef","isOpen","setIsOpen","onKeyDown","menu","keyCode","focusedElement","elementChildren","from","focus","onTrigger","containerRef","autoClose","shouldSkipTransition","success","readOnly","autoComplete","inputMode","maxLength","onInput","onKeyPress","onBlur","onPaste","labelText","htmlFor","backgroundColor","bubbleStyle","ariaLabelledBy","transformOriginX","transformOriginY","noCloseOnBackdrop","noCompact","onCloseAnimationEnd","backdropContainerRef","transitionClassNames","useShowTransition","captureEscKeyListener","useHistoryBack","useEffectWithPrevDeps","prevIsOpen","dispatchHeavyAnimationEvent","handleKeyDown","useKeyboardListNavigation","useVirtualBackdrop","bubbleClassName","transformOriginYStyle","transformOriginXStyle","IS_COMPACT_MENU","IS_BACKDROP_BLUR_SUPPORTED","props","icon","destructive","origin","ripples","setRipples","cleanUpDebounced","useMemo","debounce","button","container","position","getBoundingClientRect","rippleSize","offsetWidth","x","clientX","y","clientY","requestAnimationFrame","APP_NAME","APP_VERSION","process","DEBUG_MORE","IS_TEST","DEBUG_ALERT_MSG","PAGE_TITLE","INACTIVE_MARKER","DEBUG_PAYMENT_SMART_GLOCAL","SESSION_USER_KEY","LEGACY_SESSION_KEY","GLOBAL_STATE_CACHE_DISABLED","GLOBAL_STATE_CACHE_KEY","GLOBAL_STATE_CACHE_USER_LIST_LIMIT","GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT","GLOBAL_STATE_CACHE_CHATS_WITH_MESSAGES_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","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","CUSTOM_APPENDIX_ATTRIBUTE","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","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","STICKER_SIZE_JOIN_REQUESTS","STICKER_SIZE_INVITES","NO_STICKER_SET_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","GROUP_CALL_VOLUME_MULTIPLIER","GROUP_CALL_DEFAULT_VOLUME","ENABLE_THUMBNAIL_VIDEO","addActionHandler","importLegacySession","clearLegacySessions","apiUpdate","userAgent","navigator","PLATFORM_ENV","sessionData","loadStoredSession","isTest","search","isMovSupported","IS_MOV_SUPPORTED","isWebmSupported","IS_WEBM_SUPPORTED","phoneNumber","authIsLoading","authError","password","file","firstName","lastName","authIsLoadingQrCode","storeSession","currentUserId","clearStoredSession","_global","_actions","unsubscribe","forceWebsync","reset","forceInitApi","cacheApi","langCachePrefix","langCacheVersion","updateAppBadge","init","connectionState","authNearestCountry","getGlobal","deviceToken","subscribedAt","buildInputPrivacyRules","visibility","allowedIds","deniedIds","users","byId","usersById","chats","chatsById","rules","collectUsers","isUserId","collectChats","allowedUsers","allowedChats","blockedUsers","blockedChats","photo","bio","about","setGlobal","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","hash","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","appConfig","selectNotifySettings","setLanguage","onUpdateApiReady","wasAuthReady","authState","authorizationState","isLoggingOut","authIsCodeViaApp","isCodeViaApp","authHint","hint","authQrCode","qrCode","onUpdateAuthorizationState","onUpdateAuthorizationError","isOnAuth","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","setAttribute","toString","body","classList","IS_TOUCH_ENV","ensurePermanentWebVersion","startWebsync","IS_ANDROID","IS_MAC_OS","IS_SAFARI","uiReadyState","remove","authPhoneNumber","shouldSkipHistoryAnimations","forceSyncOnIOs","replaceThemeSettings","FOREVER_BANNED_DATE","VERIFIED_PRIORITY_BASE","PINNED_PRIORITY_BASE","entityId","isChatGroup","isChatBasicGroup","isChatSuperGroup","isChatChannel","isCommonBoxChat","isChatWithRepliesBot","getChatTypeString","getPrivateChatUserId","isSelf","getChatDescription","getChatLink","inviteLink","getChatAvatarHash","owner","avatarHash","isChatSummaryOnly","lastMessage","isChatAdmin","adminRights","getHasAdminRight","key","isUserRightBanned","currentUserBannedRights","defaultBannedRights","getCanPostInChat","threadId","isRestricted","migratedTo","isNotJoined","isCreator","getAllowedAttachmentOptions","isChatWithBot","canAttachMedia","canAttachPolls","canSendStickers","canSendGifs","canAttachEmbedLinks","isAdmin","getMessageSendingRestrictionReason","sendMessages","untilDate","formatDateToString","formatTime","getChatSlowModeOptions","slowMode","isChatArchived","folderId","selectIsChatMuted","notifySettings","notifyExceptions","isMuted","hasPrivateChatsNotifications","hasBroadcastNotifications","hasGroupNotifications","selectShouldShowMessagePreview","hasPrivateChatsMessagePreview","hasBroadcastMessagePreview","hasGroupMessagePreview","getCanDeleteChat","getFolderDescriptionText","folder","chatsCount","emoticon","pinnedChatIds","excludedChatIds","includedChatIds","excludeArchived","excludeMuted","excludeRead","values","bots","groups","channels","contacts","nonContacts","getMessageSenderName","getUserFirstOrLastName","sortChatIds","chatIds","shouldPrioritizeVerified","priorityIds","orderBy","priority","date","isVerified","filterChatsByName","searchWords","prepareSearchWordsForNeedle","getMessageHtmlId","getMessageKey","msgId","buildMessageKey","parseMessageKey","Number","getMessageOriginalId","previousLocalId","sticker","video","audio","voice","poll","webPage","contact","getMessageCustomShape","isRound","parseEmojiOnlyString","getMessageSingleEmoji","getFirstLinkInMessage","link","find","isOwnMessage","isOutgoing","isReplyMessage","replyToMessageId","isForwardedMessage","forwardInfo","isActionMessage","isServiceNotificationMessage","isAnonymousOwnMessage","senderId","getSenderTitle","getSendingState","sendingState","isMessageLocal","isHistoryClearMessage","getMessageContentFilename","isLottie","isVideo","isWebpSupported","baseFilename","IS_OPUS_SUPPORTED","areReactionsEmpty","reactions","results","l","count","isGeoLiveExpired","timestamp","period","getMessageRecentReaction","recentReactions","checkIfReactionAdded","oldReactions","newReactions","every","reaction","oldReactionsMap","acc","r","SPOILER_CHARS","noReactions","isExtended","getMessageTextWithSpoilers","accText","spoiler","fill","random","generateBrailleSpoiler","groupedId","truncatedText","summary","isGif","getMessageAudioCaption","question","performer","getMessageContent","hasMessageMedia","getMessagePhoto","getMessageVideo","getMessageDocument","getMessageSticker","getMessageContact","getMessagePoll","getMessageAction","getMessageAudio","getMessageVoice","getMessageRoundVideo","isMessageDocumentPhoto","mediaType","isMessageDocumentVideo","getMessageInvoice","getMessageLocation","getMessageWebPage","getMessageWebPagePhoto","getMessageWebPageVideo","getMessageMediaThumbDataUri","media","getMessageMediaThumbnail","dataUri","buildStaticMapHash","geo","width","height","zoom","scale","long","lat","accuracyRadius","getMessageMediaHash","webPagePhoto","webPageVideo","messageVideo","messagePhoto","mediaId","hasMessageLocalBlobUrl","getVideoOrAudioBaseHash","getAudioHasCover","IS_PROGRESSIVE_SUPPORTED","thumbnailSizes","getMessageMediaFormat","fullVideo","getMessageFileName","getMessageFileSize","blobUrl","getChatMediaMessageIds","messages","listedIds","isFromSharedMedia","getMessageContentIds","getPhotoFullDimensions","sizes","getPhotoInlineDimensions","getVideoDimensions","getMediaTransferState","isLoadNeeded","isUploading","isTransferring","transferProgress","messageIds","contentType","validator","matchLinkInMessageText","getMediaDuration","duration","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","isContact","sortUserIds","userIds","userStatusesById","getServerTime","expires","filterUsersByName","savedMessagesLang","getUserIdDividend","abs","getUserColorKey","peer","typed","typify","replaceChatListIds","newIds","listIds","updateChatListIds","idsUpdate","replaceChats","newById","updateChat","chatUpdate","updatedChat","getUpdatedChat","updatedById","keys","addChats","isUpdated","addedById","isMin","shouldOmitMinInfo","omit","photos","updateChatListType","listType","currentListIds","listTypeKey","currentFolderList","updateChatListSecondaryInfo","info","totalCountKey","orderedPinnedIds","totalChatCount","isFullyLoaded","leaveChat","leftChatId","selectChatListType","listId","addChatMembers","membersToAdd","currentMembers","members","newMemberIds","m","updatedMembers","currentIds","updatedIds","areSortedArraysEqual","updateStickerSets","category","sets","resultIds","updatedSets","stickerSet","existing","stickers","setsById","setIds","updateStickerSet","stickerSetId","currentStickerSet","addedSets","added","installedDate","updateGifSearch","isNew","nextOffset","currentResults","gifs","newResults","gif","replaceAnimatedEmojis","animatedEmojis","updateStickersForEmoji","remoteStickers","allStickers","selectStickersForEmoji","uniqueIds","unique","forEmoji","rebuildStickersForEmoji","replaceUsers","updateContactList","updatedUsers","contactUserIds","contactList","newContactUserIds","userUpdate","updatedUser","getUpdatedUser","updateUsers","deleteContact","MEMO_EMPTY_ARRAY","updateUserSearch","searchStatePartial","userSearch","updateUserSearchFetchingStatus","newState","fetchingStatus","updateUserBlockedState","isBlocked","replaceUserStatuses","statusesById","addUserStatuses","newKeys","pick","closeNewContactDialog","newContact","getComplexKey","updateGlobalSearch","globalSearch","updateGlobalSearchContent","currentContent","updateGlobalSearchResults","newFoundMessages","nextRate","resultsByType","newFoundMessagesById","foundIdsForType","foundIds","newId","updateGlobalSearchFetchingStatus","prevFoundIds","newFoundIds","prototype","foundOrPrevFoundIds","nextOffsetId","replaceLocalTextSearch","chatThreadKey","searchParams","localTextSearch","byChatThreadKey","updateLocalTextSearch","isActive","replaceLocalTextSearchResults","updateLocalTextSearchResults","orderFoundIds","replaceLocalMediaSearch","localMediaSearch","byChatId","updateLocalMediaSearchType","currentType","updateLocalMediaSearchResults","replaceLocalMediaSearchResults","sort","a","b","updateManagementProgress","management","updateManagement","newSettings","themes","notifyException","exceptionData","addNotifyException","updateTwoFaSettings","twoFaSettings","updateShippingOptions","shippingOptions","payment","setRequestInfoId","requestId","setPaymentStep","step","setInvoiceMessageInfo","photoUrl","invoiceContent","setStripeCardInfo","cardInfo","stripeCredentials","setSmartGlocalCardInfo","smartGlocalCredentials","setPaymentForm","form","setConfirmPaymentUrl","confirmPaymentUrl","setReceipt","receipt","messageInvoice","clearPayment","closeInvoice","isPaymentModalOpen","updateStatistics","statistics","updateStatisticsGraph","updateCurrentMessageList","shouldReplaceHistory","messageLists","newMessageLists","last","replaceChatMessages","updateMessageStore","updateThread","threadUpdate","threadsById","replaceThreadParam","paramName","newValue","addMessages","addedByChatId","messagesByChatId","addChatMessagesById","selectChatMessages","updateChatMessage","messageUpdate","updatedMessage","updateScheduledMessage","selectScheduledMessages","replaceScheduledMessages","deleteChatMessages","deletedForwardedPosts","pickTruthy","isLinkedChannelPost","threadInfo","selectThreadInfo","selectListedIds","outlyingIds","selectOutlyingIds","viewportIds","selectViewportIds","pinnedIds","selectPinnedIds","newMessageCount","messagesCount","currentMessageList","selectCurrentMessageList","canDeleteCurrentThread","currentThreadId","fromChatId","fromMessageId","originalPost","selectChatMessage","deleteChatScheduledMessages","scheduledIds","selectScheduledIds","updateListedIds","orderHistoryIds","updateOutlyingIds","addViewportId","safeReplaceViewportIds","newViewportIds","updateThreadInfo","newThreadInfo","updateThreadInfos","updates","scheduledMessages","updateScheduledMessages","updateFocusedMessage","noHighlight","isResizingContainer","focusedMessage","updateSponsoredMessage","sponsoredByChatId","updateFocusDirection","direction","enterMessageSelectMode","selectedMessages","toggleMessageSelection","messageListType","childMessageIds","withShift","oldSelectedMessages","selectMessageIdsByGroupId","selectedMessageIds","newMessageIds","newSelectedMessageIds","selectCurrentMessageIds","prevIndex","currentIndex","to","exitMessageSelectMode","updateThreadUnreadFromForwardedMessage","originMessage","lastMessageId","isDeleting","channelPostId","threadInfoOld","selectChat","selectIsChatWithSelf","selectIsChatWithBot","selectChatUser","selectSupportChat","isSupport","selectChatOnlineCount","onlineCount","selectChatBot","selectIsChatBotNotStarted","bot","messageInfo","selectAreActiveChatsLoaded","active","selectIsChatListed","targetList","list","selectChatFolder","chatFolders","selectIsChatPinned","archived","chatFoldersById","selectChatByUsername","usernameLowered","selectIsServiceChatReady","selectSendAs","sendAsId","selectCurrentStickerSearch","selectCurrentGifSearch","selectStickerSet","selectStickerSetByShortName","shortName","stickerSets","stickersForEmoji","favorite","packs","cleanEmoji","selectAnimatedEmoji","cleanedEmoji","selectAnimatedEmojiEffect","animatedEmojiEffects","selectAnimatedEmojiSound","emojiSounds","selectLocalAnimatedEmoji","selectLocalAnimatedEmojiEffect","selectLocalAnimatedEmojiEffectByName","selectCurrentChat","selectThreadParam","thread","selectScrollOffset","selectReplyingToId","selectEditingId","selectEditingDraft","selectEditingScheduledId","selectEditingScheduledDraft","selectDraft","selectNoWebPage","selectFirstMessageId","selectReplyStack","selectThreadOriginChat","originChannelId","selectThreadTopMessageId","topMessageId","selectThreadByMessage","replyToTopMessageId","selectIsMessageInCurrentMessageList","selectIsViewportNewest","chatMessages","selectScheduledMessage","selectEditingMessage","selectChatMessageByPollId","pollId","messageWithPoll","selectFocusedMessageId","focusedChatId","selectIsMessageFocused","focusedId","selectIsMessageUnread","lastReadOutboxMessageId","selectOutgoingStatus","isScheduledList","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","canSaveGif","noOptions","ability","selectCanDeleteSelectedMessages","messageActions","selectCanReportSelectedMessages","selectCanDownloadSelectedMessages","selectIsDownloading","activeInChat","activeDownloads","selectActiveDownloadIds","selectUploadProgress","fileUploads","byMessageLocalId","selectRealLastReadId","lastReadInboxMessageId","Infinity","selectFirstUnreadId","lastReadId","lastReadServiceNotificationId","serviceNotifications","notification","isUnread","findAfterLastReadId","isFromScheduled","found","selectIsForwardModalOpen","forwardMessages","isModalShown","selectCommonBoxChatId","fromLastMessage","selectIsInSelectMode","selectIsMessageSelected","selectForwardedMessageIdsByGroupId","selectIsDocumentGroupSelected","selectedIds","groupIds","selectSelectedMessagesCount","selectNewestMessageWithBotKeyboardButtons","findLast","keyboardButtons","replyHideMessageId","shouldHideKeyboardButtons","selectCanAutoLoadMedia","isPhoto","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","selectDefaultReaction","defaultReaction","availableReactions","isInactive","enabledReactions","selectVisibleUsers","selectShouldSchedule","selectCanScheduleUntilOnline","chatBot","selectUserStatus","selectCurrentTextSearch","currentSearch","selectCurrentMediaSearch","selectStatistics","selectManagement","selectCurrentManagementType","selectIsMediaViewerOpen","mediaViewer","avatarOwnerId","selectRightColumnContentKey","pollResults","selectIsPollResultsOpen","RightColumnContent","IS_SINGLE_COLUMN_LAYOUT","currentManagement","selectCurrentManagement","isStatisticsShown","currentChatId","canViewStatistics","selectIsStatisticsShown","newChatMembersProgress","NewChatMembersProgress","isChatInfoShown","selectIsRightColumnShown","shouldUseSystemTheme","getSystemTheme","selectCurrentGlobalSearchQuery","selectPaymentChatId","selectPaymentMessageId","selectPaymentFormId","formId","selectPaymentRequestId","selectProviderPublishableKey","nativeParams","publishableKey","selectProviderPublicToken","publicToken","selectStripeCredentials","selectSmartGlocalCredentials","selectNotifyExceptions","selectIsUserBlocked","selectUserByPhoneNumber","phoneNumberCleaned","cb","dependencies","debugKey","prevDeps","usePrevious","initial","setValue","setTrue","setFalse","setTrigger","ANIMATION_START_EVENT","ANIMATION_END_EVENT","timeout","isAnimating","isHeavyAnimating","onEnd","clearTimeout","dispatchEvent","Event","handleAnimationStart","handleAnimationEnd","isDisabled","removeEventListener","LOCATION_HASH","PATH_BASE","pathname","historyState","nextStateIndexToReplace","isHistoryAltered","isEdge","currentIndexes","disableHistoryBack","handleTouchEnd","onBack","onForward","currentState","shouldReplaceNext","hashes","indexRef","isForward","prevIsActive","isClosed","indexHashRef","prevHashes","isHashChangedFromEvent","isForceClose","prev","history","pushState","state","realDelta","indexLast","findIndex","go","replaceState","back","handlePopState","currIndex","disableHistoryAnimations","hasChanged","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","d","next","shouldSkipUndefined","onCloseTransitionEnd","noOpenTransition","noCloseTransition","setIsClosed","closeTimeoutRef","hasOpenClassName","setHasOpenClassName","exec","shouldHaveOpenClassName","isClosing","shouldRender","handleEvent","contains","NON_BUBBLEABLE_EVENTS","documentEventCounters","delegationRegistryByEventType","delegatedEventTypesByElement","propName","handler","asCapture","eventType","resolveEventType","canUseEventDelegation","addDelegatedListener","removeDelegatedListener","tagName","realEventType","resolveDelegationRegistry","newSet","resolveDelegatedEventTypes","removeAllDelegatedListeners","eventTypes","realEvent","events","furtherCallsPrevented","Proxy","p","Reflect","parentNode","documentListenersCount","delegatedHandlersCount1","counter","delegationRegistriesCount","delegatedHandlersCount2","delegationRegistry","delegationElementsCount","delegatedEventTypesCount","FILTERED_ATTRIBUTES","HTML_ATTRIBUTES","MAPPED_ATTRIBUTES","autoPlay","headsByElement","renderWithVirtual","parentEl","$current","$new","$parent","skipComponentUpdate","forceIndex","fragment","moveDirection","isCurrentComponent","isComponentElement","isNewComponent","hasElementChanged","updateComponent","componentInstance","isMounted","setupComponentUpdateListener","newTarget","getTarget","initComponent","node","createNode","setTarget","childNodes","insertBefore","appendChild","removeChild","unmountTree","replaceChild","areComponents","isRealElement","nextSibling","updateAttributes","renderChildren","$element","mountComponent","$firstChild","renderComponent","isEmptyElement","createTextNode","isTextElement","tag","entries","$child","currentEl","firstChild","child","DEBUG_checkKeyUniqueness","teactFastList","$newChild","currentRemainingIndex","remainingByKey","$currentChild","isKeyPresent","newChildKey","order","teactOrderKey","fragmentQueue","fragmentIndex","newChildren","currentPreservedIndex","currentChildInfo","flushFragmentQueue","shouldMoveNode","isMovingDown","renderFastListChildren","currentChildrenLength","newChildrenLength","createDocumentFragment","$fragmentChild","currentEntries","newEntries","currentValue","cssText","removeAttribute","__html","render","headId","getAttribute","$head","VirtualElementTypesEnum","Fragment","Symbol","DEBUG_SILENT_RENDERS_FOR","renderingInstance","Empty","Text","isTagElement","Tag","Component","flatten","createComponentInstance","buildTagElement","parsedChildren","hooks","cursor","byCursor","effects","memos","buildComponentElement","dropEmptyTail","buildChildElement","isEmptyPlaceholder","DEBUG_components","newRenderedValue","DEBUG_startAt","componentName","renderCount","renderTimes","performance","handleError","renderedValue","newChild","$old","memoContainer","cleanup","hook","effect","nextValue","setter","helpGc","prepareComponentForFrame","prepareForFrame","throttleWithPrimaryRaf","throttleWithRaf","forceUpdateComponent","currentElement","componentElement","DEBUG_contentComponentName","useLayoutEffectBase","schedulerFn","primarySchedulerFn","execCleanup","dependency","causedBy","res","prevValue","fastRaf","fastRafPrimary","useLayoutEffect","onTickEnd","onTickEndPrimary","resolver","getUnequalProps","newCallback","currentGlobal","actionHandlers","callbacks","containers","mapStateToProps","ownProps","mappedProps","newMappedProps","isNaN","DEBUG_componentName","arePropsShallowEqual","areMappedPropsChanged","DEBUG_updates","updateTime","runCallbacksThrottled","throttleWithTickEnd","runCallbacks","forceOnHeavyAnimation","newGlobal","handleAction","addCallback","removeCallback","TeactNContainer","vs16RegExp","zeroWidthJoiner","rawEmoji","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","unreadCount","setAppBadge","currentProps","newProps","currentKeys","currentKeysLength","prop","elementName","baseName","modifiers","modifier","self","caches","Type","fetch","cacheName","isHtmlAllowed","request","Request","cache","open","headers","Blob","blob","shouldRecreate","resolvedType","Json","json","save","cacheData","Response","put","clear","createCallbackManager","hasCallbacks","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","CLIPBOARD_ITEM_SUPPORTED","clipboard","ClipboardItem","textCopyEl","str","selection","getSelection","rangeToRestore","rangeCount","getRangeAt","select","execCommand","removeAllRanges","addRange","copyImageToClipboard","imageUrl","canvas","ctx","getContext","imageEl","Image","onload","img","drawImage","toBlob","copyBlobToClipboard","pngBlob","write","WEEKDAYS_FULL","MONTHS_FULL","MONTHS_FULL_LOWERCASE","month","MILLISECONDS_IN_DAY","isToday","getDayStartAt","getDayStart","datetime","toYearMonth","getFullYear","getMonth","toIsoString","hours","getHours","marker","padStart","getMinutes","formatPastTimeShort","weekAgo","getDay","withYear","format","formatDate","formatMonthAndYear","isShort","formatCountdown","msLeft","days","formatMediaDuration","formatCountdownShort","ceil","formatLastUpdated","currentTime","lastUpdated","seconds","formatHumanDate","noWeekdays","isUpperFirst","upperFirst","lowerFirst","weekAhead","weekDay","formatKey","day","monthIndex","formatMediaDateTime","maxValue","minutes","maxHours","maxMinutes","string","formatVoiceRecordDuration","durationInMs","milliseconds","formatDayToStringWithCache","withCache","dayStartAt","locale","toLocaleString","year","formatDateTimeToString","hour","minute","second","isValidDate","MAX_MONTH_IN_YEAR","parseDateString","matchStringDate","matchEuropeStringDate","matchNumberDate","dateParts","timestampPlusDay","EXCLUDE_EMOJIS","EMOJI_EXCEPTIONS","unifiedToNative","unified","codePoints","parseInt","fromCodePoint","regex","replacement","pairs","uncompressEmoji","emojiData","categories","emojiRaw","names","native","image","isoToEmoji","iso","test","codePointAt","isWebpSupportedCache","webp","handleLoadOrError","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","IS_REQUEST_FULLSCREEN_SUPPORTED","ARE_CALLS_SUPPORTED","LAYERS_ANIMATION_NAME","TEST_VIDEO","DPR","devicePixelRatio","MASK_IMAGE_DISABLED","CSS","supports","IS_SCROLL_PATCH_NEEDED","MESSAGE_LIST_SENSITIVE_AREA","dataUriToBlob","arr","mime","bstr","atob","u8arr","Uint8Array","blobToDataUri","reader","FileReader","readAsDataURL","blobToFile","File","lastModified","preloadImage","preloadVideo","volume","onloadedmetadata","createPosterForVideo","onseeked","videoWidth","videoHeight","toDataURL","fetchBlob","fetchFile","imgToCanvas","constructor","fileBits","rest","super","this","initials","buildInitials","prevGlobal","prepared","updateFolderManagerThrottled","throttle","onIdle","updateFolderManager","inited","getOrderedIds","orderedIdsByFolderId","getPinnedChatsCount","pinnedCountByFolderId","getChatsCount","chatsCountByFolderId","getUnreadCounters","unreadCountersByFolderId","getAllNotificationsCount","notificationsCount","addOrderedIdsCallback","addChatsCountCallback","addUnreadCountersCallback","DEBUG_startedAt","isAllFolderChanged","isMainFolderChanged","isArchivedFolderChanged","isAllFullyLoadedChanged","isAllFolderFullyLoaded","isArchivedFullyLoadedChanged","isArchivedFolderFullyLoaded","areFoldersChanged","foldersById","areChatsChanged","areUsersChanged","areNotifySettingsChanged","areNotifyExceptionsChanged","affectedFolderIds","emptyFolderIds","folderSummariesById","updateFullyLoaded","updateResults","prevAllFolderListIds","allFolderListIds","prevArchivedFolderListIds","archivedFolderListIds","changedFolders","newListIds","newPinnedIds","buildFolderSummaryFromMainList","allFolderPinnedIds","archivedFolderPinnedIds","newFoldersById","buildFolderSummary","updateFolders","newChatsById","newUsersById","newNotifySettings","newNotifyExceptions","folderSummaries","newAllFolderListIds","newArchivedFolderListIds","allIds","newFolderIds","currentSummary","chatSummariesById","newSummary","unreadMentionsCount","hasUnreadMark","joinDate","draftDate","userInfo","isListed","isArchived","isUserContact","buildChatSummary","chatSummary","folderSummary","isChatInFolder","buildChatFolderIds","currentFolderIds","folderIdsByChatId","deletedFolderIds","currentFolderIdsSet","newFolderIdsSet","currentFolderOrderedIds","chatIdsByFolderId","isOrderedListJustPatched","updateListsForChat","currentPinnedIds","wasUnreadCountersChanged","wasChatsCountChanged","pinnedCount","newPinnedCount","orderedIds","newOrderedIds","prevOrderedIds","sortedPinnedIds","allListIds","sortedNotPinnedIds","chatId1","chatId2","buildFolderOrderedIds","currentOrderedIds","currentPinnedCount","currentChatsCount","newChatsCount","currentUnreadCounters","newUnreadCounters","buildFolderUnreadCounters","newInitials","totalPrice","Intl","NumberFormat","store","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","BOT_PRECHECKOUT_TIMEOUT","SHIPPING_ERRORS","getReadableErrorText","isSlowMode","textParams","extraPartIndex","errorMessage","handleErrorEvent","ErrorEvent","reason","alert","collection","member","mapValues","newByKey","object","stringKeys","orderRule","mode","compareValues","currentOrderRule","isAsc","aValue","bValue","mode1","mode2","orderRule1","orderRule2","isAsc1","isAsc2","array","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","currentLangCode","currentTimeFormat","cacheValue","cached","langString","processTranslation","importFallbackLangPack","getTranslationForLangString","translateString","remoteLangPack","remote","fetchRemoteString","withFallback","newLangPack","fetchRemote","langInfo","rtl","default","sourceLangPacks","template","optionIndex","getPluralOption","translationSlices","initialValue","processTemplate","formatInteger","SAMPLE_RATE","oggToWav","opusData","arrayBuffer","typedArray","decoderWorker","wavWorker","onmessage","buffers","buffer","page","terminate","wavBitDepth","wavSampleRate","decoderSampleRate","outputBufferSampleRate","pages","asCacheApiType","memoryCache","fetchPromises","progressCallbacks","cancellableCallbacks","mediaFormat","onProgress","callbackUniqueId","getProgressive","fetchFromCacheOrRemote","activeCallbacks","getFromMemory","cancelProgress","parentCallback","progressiveUrl","mediaPng","webpToPng","prepareMedia","mediaSource","MediaSource","streamUrl","sourceBuffer","addSourceBuffer","makeOnProgress","revokeObjectURL","endOfStream","appendBuffer","mediaData","serviceWorker","fullSize","controller","Bundles","LOAD_PROMISES","MEMORY_CACHE","Auth","Main","Extra","Calls","bundle","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","notifyAboutMessage","isReaction","resultSettings","resultExceptions","loadNotificationSettings","hasFocus","checkIfShouldNotify","areNotificationsSupported","activeReaction","imageHash","mediaLoader","getAvatar","messageSender","messageAction","actionTargetMessage","targetUserIds","actionTargetUserIds","actionTargetChatId","actionTargetUsers","privateChatUserId","privateChatUser","isChat","senderName","getNotificationContent","badge","vibrate","onclick","close","startActiveReaction","onshow","closeMessageNotifications","notifyClientReady","PERMANENT_VERSION_KEY","AVAILABLE_VERSIONS","setPermanentWebVersion","version","hasPermanentWebVersion","PATTERN_PLACEHOLDER","DEFAULT_PATTERN","getCountryCodesByIso","phoneCodeList","country","iso2","getCountryFromPhoneNumber","possibleCountries","countryCode","codesWithPrefix","prefixes","prefix","bestMatches","formatPhoneNumber","pattern","numberWithoutCode","patterns","defaultPattern","stripped","getBestPattern","formatPhoneNumberWithCode","numberWithPlus","createMessageHash","messageList","typeOrThreadId","parseLocationHash","isType","fn","waitingTimeout","shouldRunFirst","shouldRunLast","interval","isPending","_args","setInterval","clearInterval","throttleWith","waiting","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","tryIdb","intervalId","onupgradeneeded","createObjectStore","txMode","db","transaction","objectStore","createStore","DC_IDS","hasStoredSession","withLegacy","userAuthJson","dcID","dcId","removeItem","sessionId","sessionJson","customStore","idb","idbKeys","getAllKeys","items","openCursor","continue","eachCursor","isInitialized","HEX_COLOR_REGEX","RGB_VARIABLES","lerp","start","end","interpolationRatio","colors","themeColors","property","hexToRgb","hex","g","applyColorAnimationStep","startIndex","endIndex","propertyColors","withAnimation","isDarkTheme","shouldAnimate","startAt","themeColorTag","querySelector","transition","formatFixedNumber","formatIntegerCompact","views","getFirstLetters","phrase","word","EMPTY_IMAGE_DATA_URI","initWebpWorker","wasmReady","requests","getDecodePromise","ImageData","putImageData","createPng","webpToPngBase64","handleLibWebpMessage","WEBSYNC_URLS","WEBSYNC_VERSION","WEBSYNC_KEY","getTs","lastTimeout","authed","currentTs","canRedirect","ts","script","removeElement","URLSearchParams","saveSync","clearWebsync","IS_LANDSCAPE","isLandscape","initialHeight","currentWindowSize","updateSizes","isRefreshDisabled","handleResize","visualViewport","pageTop","vh","getIsKeyboardVisible","disableRefresh","enableRefresh","WeakMap","fnCache","cacheKey","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","exports","__webpack_modules__","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","registrations","getRegistrations","unregister","register","hasErrorKey","INITIAL_STATE","isLeftColumnShown","phoneCodes","general","groupCalls","activeChatFolder","recentEmojis","recent","greeting","featured","emojiKeywords","saved","inlineBots","byUsername","topPeers","topInlineBots","playbackRate","audioPlayer","notifications","dialogs","messageSendKeyCombo","autoLoadFileMaxSizeMb","shouldSuggestStickers","isConnectionStatusMinimized","light","isBlurred","patternColor","dark","activeReactions","shouldShowContextMenuHint","updateCacheThrottled","updateCache","unsubscribeFromBeforeUnload","isCaching","setupCaching","clearCaching","reducedGlobal","reduceShowChatInfo","reduceUsers","reduceChats","reduceMessages","recentlyFoundChatIds","reduceSettings","reduceChatFolders","reduceGroupCalls","reduceAvailableReactions","visibleUserIds","idsToSave","currentChat","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","reactionThumbsPath","telegramLogoPath","authCode","monkeyPath","authPassword","background","hasCustomBackground","hasCustomBackgroundColor","isRightColumnShown","leftColumnWidth","setIsUiReady","isReady","markReady","shouldRenderMask","safePreload","translation","setTranslation","getSuggestedLanguage","suggestedLanguage","MENU_HIDING_DURATION","inputRef","setFilter","filteredList","setFilteredList","updateFilter","filterValue","defaultName","getFilteredList","prevPhoneCodeList","handleInput","handleInputKeyDown","CodeInput","handleTrigger","formEl","getElementById","scrollTo","top","scrollHeight","behavior","inputValue","Spinner","DropdownMenu","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","colorStops","createLinearGradient","apply","createRadialGradient","addColorStop","A","minVersion","maxVersion","ecLevel","radius","quiet","HTMLCanvasElement","clearRect","S","multiply","L","M","Q","returnToAuthPhoneNumber","qrCodeRef","token","isMobile","windowSize","AuthQrCode","appInactivePath","renderMain","disconnect","markInactive","TeactDOM"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"main.040a86fe9347e4854db9.js","mappings":"uBACIA,EADAC,ECAAC,EACAC,ECwCAC,EASAC,E,wFC/BJ,IAAIC,EACJ,MAAMC,EAAgB,IAAIC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,EAAAA,IAAQ,GAc3C,IAZAU,EAAAA,EAAAA,KAAU,MACR64E,EAAAA,EAAAA,KfTFxrF,EeU6B,KACzB29F,IACAx1F,SAASX,MAAS,GAAEuX,EAAAA,KAAaC,EAAAA,KAEjC4+E,OAED,CAACD,EAAYC,IAIZx8C,EACF,OAAO,mBAAC,GAAD,MAGT,GAAIpzB,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,OAAO0vE,KAIb,OAAO5W,EAAAA,EAAAA,KAAiB,GAAQ4W,KAAe,mBAAC,GAAD,SC1C7C1+F,EAAAA,IAEFC,QAAQC,IAAI,aAGduH,EAAAA,EAAAA,MAAaihB,OAET1oB,EAAAA,IAEFC,QAAQC,IAAI,4BAGd2+F,EAAAA,EAAAA,OACE,mBAAC,GAAD,MACA11F,SAAS+uF,eAAe,SAGtBl4F,EAAAA,IAEFC,QAAQC,IAAI,6BAGdiJ,SAAS9I,iBAAiB,YAAY,KAEpCJ,QAAQ4B,KAAK,gBAAgBgnB,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/renderMessageText.ts","webpack://telegram-t/./src/components/common/helpers/renderText.tsx","webpack://telegram-t/./src/components/common/spoiler/Spoiler.tsx","webpack://telegram-t/./src/components/common/helpers/renderTextWithEntities.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/global/actions/api/initial.ts","webpack://telegram-t/./src/global/actions/api/settings.ts","webpack://telegram-t/./src/global/actions/apiUpdaters/initial.ts","webpack://telegram-t/./src/global/actions/ui/initial.ts","webpack://telegram-t/./src/global/actions/ui/settings.ts","webpack://telegram-t/./src/global/helpers/chats.ts","webpack://telegram-t/./src/global/helpers/messages.ts","webpack://telegram-t/./src/global/helpers/reactions.ts","webpack://telegram-t/./src/global/helpers/messageSummary.ts","webpack://telegram-t/./src/global/helpers/messageMedia.ts","webpack://telegram-t/./src/global/helpers/localSearch.ts","webpack://telegram-t/./src/global/helpers/payments.ts","webpack://telegram-t/./src/global/helpers/users.ts","webpack://telegram-t/./src/global/index.ts","webpack://telegram-t/./src/global/reducers/chats.ts","webpack://telegram-t/./src/global/reducers/symbols.ts","webpack://telegram-t/./src/global/reducers/users.ts","webpack://telegram-t/./src/global/reducers/globalSearch.ts","webpack://telegram-t/./src/global/reducers/localSearch.ts","webpack://telegram-t/./src/global/reducers/management.ts","webpack://telegram-t/./src/global/reducers/settings.ts","webpack://telegram-t/./src/global/reducers/twoFaSettings.ts","webpack://telegram-t/./src/global/reducers/payments.ts","webpack://telegram-t/./src/global/reducers/statistics.ts","webpack://telegram-t/./src/global/reducers/messages.ts","webpack://telegram-t/./src/global/selectors/chats.ts","webpack://telegram-t/./src/global/selectors/symbols.ts","webpack://telegram-t/./src/global/selectors/messages.ts","webpack://telegram-t/./src/global/selectors/localSearch.ts","webpack://telegram-t/./src/global/selectors/statistics.ts","webpack://telegram-t/./src/global/selectors/management.ts","webpack://telegram-t/./src/global/selectors/ui.ts","webpack://telegram-t/./src/global/selectors/globalSearch.ts","webpack://telegram-t/./src/global/selectors/payments.ts","webpack://telegram-t/./src/global/selectors/settings.ts","webpack://telegram-t/./src/global/selectors/users.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/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/callbacks.ts","webpack://telegram-t/./src/util/captureEscKeyListener.ts","webpack://telegram-t/./src/util/captureKeyboardListeners.ts","webpack://telegram-t/./src/util/clipboard.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/folderManager.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/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/index.js","webpack://telegram-t/./node_modules/safari-14-idb-fix/dist/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/./src/util/withCache.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/initialState.ts","webpack://telegram-t/./src/global/cache.ts","webpack://telegram-t/./src/global/init.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 = {\"13\":1,\"133\":1,\"395\":1,\"472\":1,\"616\":1,\"654\":1,\"878\":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 { Api } from '../../../lib/gramjs';\nimport { ApiInitialArgs, ApiOnProgress, OnApiUpdate } from '../../types';\nimport { Methods, MethodArgs, MethodResponse } from '../methods/types';\nimport { WorkerMessageEvent, 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 const promise = makeRequest({\n type: 'callMethod',\n name: fnName,\n args,\n });\n\n // Some TypeScript magic to make sure `VirtualClass` is never returned from any method\n if (DEBUG) {\n (async () => {\n try {\n type ForbiddenTypes =\n Api.VirtualClass\n | (Api.VirtualClass | undefined)[];\n type ForbiddenResponses =\n ForbiddenTypes\n | (AnyLiteral & { [k: string]: ForbiddenTypes });\n\n // Unwrap all chained promises\n const response = await promise;\n // Make sure responses do not include `VirtualClass` instances\n const allowedResponse: Exclude = response;\n // Suppress \"unused variable\" constraint\n void allowedResponse;\n } catch (err) {\n // Do noting\n }\n })();\n }\n\n return promise 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\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', () => {\n void ensureWorkerPing();\n // Sometimes a single check is not enough\n setTimeout(() => ensureWorkerPing(), 1000);\n });\n}\n\nasync function ensureWorkerPing() {\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","// 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 | ArrayBuffer;\nexport type ApiPreparedMedia = 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 isLottie: boolean;\n isVideo: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isLottie?: true;\n isVideos?: 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\ninterface ApiGeoPoint {\n long: number;\n lat: number;\n accessHash: string;\n accuracyRadius?: number;\n}\n\ninterface ApiGeo {\n type: 'geo';\n geo: ApiGeoPoint;\n}\n\ninterface ApiVenue {\n type: 'venue';\n geo: ApiGeoPoint;\n title: string;\n address: string;\n provider: string;\n venueId: string;\n venueType: string;\n}\n\ninterface ApiGeoLive {\n type: 'geoLive';\n geo: ApiGeoPoint;\n heading?: number;\n period: number;\n}\n\nexport type ApiLocation = ApiGeo | ApiVenue | ApiGeoLive;\n\nexport type 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 Spoiler = 'MessageEntitySpoiler',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: string;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n location?: ApiLocation;\n };\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 reactors?: {\n nextOffset?: string;\n count: number;\n reactions: ApiUserReaction[];\n };\n reactions?: ApiReactions;\n}\n\nexport interface ApiReactions {\n canSeeList?: boolean;\n results: ApiReactionCount[];\n recentReactions?: ApiUserReaction[];\n}\n\nexport interface ApiUserReaction {\n userId: string;\n reaction: string;\n}\n\nexport interface ApiReactionCount {\n isChosen?: boolean;\n count: number;\n reaction: string;\n}\n\nexport interface ApiAvailableReaction {\n selectAnimation?: ApiDocument;\n staticIcon?: ApiDocument;\n centerIcon?: ApiDocument;\n aroundAnimation?: ApiDocument;\n reaction: string;\n title: string;\n isInactive?: 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' | 'illegalDrugs' | 'personalDetails' | '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 { getActions } from '../../global';\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?: React.ReactNode;\n isRtl?: boolean;\n};\n\nconst SafeLink: FC = ({\n url,\n text,\n className,\n children,\n isRtl,\n}) => {\n const { toggleSafeLinkModal, openTelegramLink } = getActions();\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","import 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\nconst parseEmojiOnlyString = (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\nexport default parseEmojiOnlyString;\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 { getActions } from '../../global';\n\ntype OwnProps = {\n className?: string;\n sender?: ApiUser | ApiChat;\n children: React.ReactNode;\n};\n\nconst UserLink: FC = ({\n className, sender, children,\n}) => {\n const { openChat } = getActions();\n\n const handleClick = useCallback(() => {\n if (sender) {\n openChat({ id: sender.id });\n }\n }, [sender, openChat]);\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 { getActions } from '../../global';\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: React.ReactNode;\n};\n\nconst MessageLink: FC = ({\n className, message, children,\n}) => {\n const { focusMessage } = getActions();\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 { getActions } from '../../global';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n chatId?: string;\n children: React.ReactNode;\n};\n\nconst ChatLink: FC = ({\n className, chatId, children,\n}) => {\n const { openChat } = getActions();\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 { getActions } from '../../global';\n\ntype OwnProps = {\n className?: string;\n groupCall?: Partial;\n children: React.ReactNode;\n};\n\nconst GroupCallLink: FC = ({\n className, groupCall, children,\n}) => {\n const { joinGroupCall } = getActions();\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 getMessageSummaryText,\n getUserFullName,\n} from '../../../global/helpers';\nimport trimText from '../../../util/trimText';\nimport { formatCurrency } from '../../../util/formatCurrency';\nimport { TextPart, renderMessageSummary } 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 RenderOptions {\n asPlainText?: boolean;\n asTextWithSpoilers?: boolean;\n}\n\nconst MAX_LENGTH = 32;\nconst NBSP = '\\u00A0';\n\nexport function renderActionMessageText(\n lang: LangFn,\n message: ApiMessage,\n actionOriginUser?: ApiUser,\n actionOriginChat?: ApiChat,\n targetUsers?: ApiUser[],\n targetMessage?: ApiMessage,\n targetChatId?: string,\n options: RenderOptions = {},\n) {\n if (!message.content.action) {\n return [];\n }\n\n const {\n text, translationValues, amount, currency, call,\n } = message.content.action;\n const content: TextPart[] = [];\n const noLinks = options.asPlainText || options.asTextWithSpoilers;\n const translationKey = text === 'Chat.Service.Group.UpdatedPinnedMessage1' && !targetMessage\n ? 'Message.PinnedGenericMessage'\n : text;\n\n let unprocessed = lang(translationKey, 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 actionOriginUser ? (\n renderUserContent(actionOriginUser, noLinks) || NBSP\n ) : actionOriginChat ? (\n renderChatContent(lang, actionOriginChat, noLinks) || 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, noLinks)).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, options)\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, noLinks)\n : 'another chat',\n );\n content.push(...processed);\n\n if (options.asPlainText) {\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: RenderOptions = {}) {\n const { asPlainText, asTextWithSpoilers } = options;\n\n if (asPlainText) {\n return getMessageSummaryText(lang, message, undefined, MAX_LENGTH);\n }\n\n const messageSummary = renderMessageSummary(lang, message, undefined, undefined, MAX_LENGTH);\n\n if (asTextWithSpoilers) {\n return (\n {messageSummary}\n );\n }\n\n return (\n {messageSummary}\n );\n}\n\nfunction renderGroupCallContent(groupCall: Partial, text: TextPart[]): string | TextPart | undefined {\n return (\n \n {text}\n \n );\n}\n\nfunction renderUserContent(sender: ApiUser, noLinks?: boolean): string | TextPart | undefined {\n const text = trimText(getUserFullName(sender), MAX_LENGTH);\n\n if (noLinks) {\n return text;\n }\n\n return {sender && renderText(text!)};\n}\n\nfunction renderChatContent(lang: LangFn, chat: ApiChat, noLinks?: boolean): string | TextPart | undefined {\n const text = trimText(getChatTitle(lang, chat), MAX_LENGTH);\n\n if (noLinks) {\n return text;\n }\n\n return {chat && renderText(text!)};\n}\n\nfunction renderMigratedContent(chatId: string, noLinks?: boolean): string | TextPart | undefined {\n const text = 'another chat';\n\n if (noLinks) {\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 { ApiMessage, ApiMessageEntityTypes } from '../../../api/types';\nimport {\n getMessageSummaryDescription,\n getMessageSummaryEmoji,\n getMessageSummaryText,\n getMessageText,\n TRUNCATED_SUMMARY_LENGTH,\n} from '../../../global/helpers';\nimport { LangFn } from '../../../hooks/useLang';\nimport renderText from './renderText';\nimport { renderTextWithEntities, TextPart } from './renderTextWithEntities';\nimport trimText from '../../../util/trimText';\n\nexport type { TextPart };\n\nexport function renderMessageText(\n message: ApiMessage,\n highlight?: string,\n shouldRenderHqEmoji?: boolean,\n isSimple?: boolean,\n truncateLength?: number,\n) {\n const { text, entities } = message.content.text || {};\n\n if (!text) {\n const contentNotSupportedText = getMessageText(message);\n return contentNotSupportedText ? [trimText(contentNotSupportedText, truncateLength)] : undefined;\n }\n\n return renderTextWithEntities(\n trimText(text, truncateLength),\n entities,\n highlight,\n shouldRenderHqEmoji,\n undefined,\n message.id,\n isSimple,\n );\n}\n\nexport function renderMessageSummary(\n lang: LangFn,\n message: ApiMessage,\n noEmoji = false,\n highlight?: string,\n truncateLength = TRUNCATED_SUMMARY_LENGTH,\n): TextPart[] {\n const { entities } = message.content.text || {};\n\n const hasSpoilers = entities?.some((e) => e.type === ApiMessageEntityTypes.Spoiler);\n if (!hasSpoilers) {\n const text = trimText(getMessageSummaryText(lang, message, noEmoji), truncateLength);\n\n if (highlight) {\n return renderText(text, ['emoji', 'highlight'], { highlight });\n } else {\n return renderText(text);\n }\n }\n\n const emoji = !noEmoji && getMessageSummaryEmoji(message);\n const emojiWithSpace = emoji ? `${emoji} ` : '';\n\n const text = renderMessageText(message, highlight, undefined, true, truncateLength);\n const description = getMessageSummaryDescription(lang, message, text);\n\n return [\n emojiWithSpace,\n ...(Array.isArray(description) ? description : [description]),\n ].filter(Boolean);\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';\nimport { compact } from '../../../util/iteratees';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\n\ntype TextPart = string | Element;\nexport type TextFilter = (\n 'escape_html' | 'hq_emoji' | 'emoji' | 'emoji_html' | 'br' | 'br_html' | 'highlight' | 'links' |\n 'simple_markdown' | 'simple_markdown_html'\n);\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 = ['emoji'],\n params?: { highlight: string | undefined },\n): TextPart[] {\n if (typeof part !== 'string') {\n return [part];\n }\n\n return compact(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 { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect, useRef,\n} from '../../../lib/teact/teact';\n\nimport { createClassNameBuilder } from '../../../util/buildClassName';\nimport useFlag from '../../../hooks/useFlag';\n\nimport './Spoiler.scss';\n\ntype OwnProps = {\n children?: React.ReactNode;\n messageId?: number;\n};\n\nconst READING_SYMBOLS_PER_SECOND = 23; // Heuristics\nconst MIN_HIDE_TIMEOUT = 5000; // 5s\nconst MAX_HIDE_TIMEOUT = 60000; // 1m\n\nconst actionsByMessageId: Map = new Map();\n\nconst buildClassName = createClassNameBuilder('Spoiler');\n\nconst Spoiler: FC = ({\n children,\n messageId,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const contentRef = useRef(null);\n\n const [isRevealed, reveal, conceal] = useFlag();\n\n const handleClick = useCallback((e: ReactMouseEvent) => {\n e.preventDefault();\n e.stopPropagation();\n\n actionsByMessageId.get(messageId!)?.forEach((actions) => actions.reveal());\n\n const contentLength = contentRef.current!.innerText.length;\n const readingMs = Math.round(contentLength / READING_SYMBOLS_PER_SECOND) * 1000;\n const timeoutMs = Math.max(MIN_HIDE_TIMEOUT, Math.min(readingMs, MAX_HIDE_TIMEOUT));\n\n setTimeout(() => {\n actionsByMessageId.get(messageId!)?.forEach((actions) => actions.conceal());\n conceal();\n }, timeoutMs);\n }, [conceal, messageId]);\n\n useEffect(() => {\n if (!messageId) {\n return undefined;\n }\n\n if (actionsByMessageId.has(messageId)) {\n actionsByMessageId.get(messageId)!.push({ reveal, conceal });\n } else {\n actionsByMessageId.set(messageId, [{ reveal, conceal }]);\n }\n\n return () => {\n actionsByMessageId.delete(messageId);\n };\n }, [conceal, handleClick, isRevealed, messageId, reveal]);\n\n return (\n \n \n {children}\n \n \n );\n};\n\nexport default memo(Spoiler);\n","import { MouseEvent } from 'react';\nimport React from '../../../lib/teact/teact';\nimport { getActions } from '../../../global';\n\nimport { ApiFormattedText, ApiMessageEntity, ApiMessageEntityTypes } from '../../../api/types';\nimport renderText, { TextFilter } from './renderText';\nimport { copyTextToClipboard } from '../../../util/clipboard';\nimport { getTranslation } from '../../../util/langProvider';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\nimport Spoiler from '../spoiler/Spoiler';\n\nexport type TextPart =\n string\n | Element;\n\ninterface IOrganizedEntity {\n entity: ApiMessageEntity;\n organizedIndexes: Set;\n nestedEntities: IOrganizedEntity[];\n}\n\nexport function renderTextWithEntities(\n text: string,\n entities?: ApiMessageEntity[],\n highlight?: string,\n shouldRenderHqEmoji?: boolean,\n shouldRenderAsHtml?: boolean,\n messageId?: number,\n isSimple?: boolean,\n) {\n if (!entities || !entities.length) {\n return renderMessagePart(text, highlight, shouldRenderHqEmoji, shouldRenderAsHtml, isSimple);\n }\n\n const result: TextPart[] = [];\n let deleteLineBreakAfterPre = false;\n\n const organizedEntities = organizeEntities(entities);\n\n // Recursive function to render regular and nested entities\n function renderEntity(\n textPartStart: number,\n textPartEnd: number,\n organizedEntity: IOrganizedEntity,\n isLastEntity: boolean,\n ) {\n const renderResult: TextPart[] = [];\n const { entity, nestedEntities } = organizedEntity;\n const { offset, length, type } = entity;\n\n // Render text before the entity\n let textBefore = text.substring(textPartStart, offset);\n const textBeforeLength = textBefore.length;\n if (textBefore) {\n if (deleteLineBreakAfterPre && textBefore.length > 0 && textBefore[0] === '\\n') {\n textBefore = textBefore.substr(1);\n deleteLineBreakAfterPre = false;\n }\n if (textBefore) {\n renderResult.push(...renderMessagePart(\n textBefore, highlight, shouldRenderHqEmoji, shouldRenderAsHtml, isSimple,\n ) as TextPart[]);\n }\n }\n\n const entityStartIndex = textPartStart + textBeforeLength;\n const entityEndIndex = entityStartIndex + length;\n\n let entityContent: TextPart = text.substring(offset, offset + length);\n const nestedEntityContent: TextPart[] = [];\n\n if (deleteLineBreakAfterPre && entityContent.length > 0 && entityContent[0] === '\\n') {\n entityContent = entityContent.substr(1);\n deleteLineBreakAfterPre = false;\n }\n\n if (type === ApiMessageEntityTypes.Pre) {\n deleteLineBreakAfterPre = true;\n }\n\n // Render nested entities, if any\n if (nestedEntities.length) {\n let nestedIndex = entityStartIndex;\n\n nestedEntities.forEach((nestedEntity, nestedEntityIndex) => {\n const {\n renderResult: nestedResult,\n entityEndIndex: nestedEntityEndIndex,\n } = renderEntity(\n nestedIndex,\n entityEndIndex,\n nestedEntity,\n nestedEntityIndex === nestedEntities.length - 1,\n );\n\n nestedEntityContent.push(...nestedResult);\n nestedIndex = nestedEntityEndIndex;\n });\n }\n\n // Render the entity itself\n const newEntity = shouldRenderAsHtml\n ? processEntityAsHtml(entity, entityContent, nestedEntityContent)\n : processEntity(entity, entityContent, nestedEntityContent, highlight, messageId, isSimple);\n\n if (Array.isArray(newEntity)) {\n renderResult.push(...newEntity);\n } else {\n renderResult.push(newEntity);\n }\n\n // Render text after the entity, if it is the last entity in the text,\n // or the last nested entity inside of another entity\n if (isLastEntity && entityEndIndex < textPartEnd) {\n let textAfter = text.substring(entityEndIndex, textPartEnd);\n if (deleteLineBreakAfterPre && textAfter.length > 0 && textAfter[0] === '\\n') {\n textAfter = textAfter.substring(1);\n }\n if (textAfter) {\n renderResult.push(...renderMessagePart(\n textAfter, highlight, shouldRenderHqEmoji, shouldRenderAsHtml, isSimple,\n ) as TextPart[]);\n }\n }\n\n return {\n renderResult,\n entityEndIndex,\n };\n }\n\n // Process highest-level entities\n let index = 0;\n\n organizedEntities.forEach((entity, arrayIndex) => {\n const { renderResult, entityEndIndex } = renderEntity(\n index,\n text.length,\n entity,\n arrayIndex === organizedEntities.length - 1,\n );\n\n result.push(...renderResult);\n index = entityEndIndex;\n });\n\n return result;\n}\n\nexport function getTextWithEntitiesAsHtml(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\nfunction renderMessagePart(\n content: TextPart | TextPart[],\n highlight?: string,\n shouldRenderHqEmoji?: boolean,\n shouldRenderAsHtml?: boolean,\n isSimple?: boolean,\n) {\n if (Array.isArray(content)) {\n const result: TextPart[] = [];\n\n content.forEach((c) => {\n result.push(...renderMessagePart(c, highlight, shouldRenderHqEmoji, shouldRenderAsHtml, isSimple));\n });\n\n return result;\n }\n\n if (shouldRenderAsHtml) {\n return renderText(content, ['escape_html', 'emoji_html', 'br_html']);\n }\n\n const emojiFilter = shouldRenderHqEmoji ? 'hq_emoji' : 'emoji';\n\n const filters: TextFilter[] = [emojiFilter];\n if (!isSimple) {\n filters.push('br');\n }\n\n if (highlight) {\n return renderText(content, filters.concat('highlight'), { highlight });\n } else {\n return renderText(content, filters);\n }\n}\n\n// Organize entities in a tree-like structure to better represent how the text will be displayed\nfunction organizeEntities(entities: ApiMessageEntity[]) {\n const organizedEntityIndexes: Set = new Set();\n const organizedEntities: IOrganizedEntity[] = [];\n\n entities.forEach((entity, index) => {\n if (organizedEntityIndexes.has(index)) {\n return;\n }\n\n const organizedEntity = organizeEntity(entity, index, entities, organizedEntityIndexes);\n if (organizedEntity) {\n organizedEntity.organizedIndexes.forEach((organizedIndex) => {\n organizedEntityIndexes.add(organizedIndex);\n });\n\n organizedEntities.push(organizedEntity);\n }\n });\n\n return organizedEntities;\n}\n\nfunction organizeEntity(\n entity: ApiMessageEntity,\n index: number,\n entities: ApiMessageEntity[],\n organizedEntityIndexes: Set,\n): IOrganizedEntity | undefined {\n const { offset, length } = entity;\n const organizedIndexes = new Set([index]);\n\n if (organizedEntityIndexes.has(index)) {\n return undefined;\n }\n\n // Determine any nested entities inside current entity\n const nestedEntities: IOrganizedEntity[] = [];\n const parsedNestedEntities = entities\n .filter((e, i) => i > index && e.offset >= offset && e.offset < offset + length)\n .map((e) => organizeEntity(e, entities.indexOf(e), entities, organizedEntityIndexes))\n .filter(Boolean as any);\n\n parsedNestedEntities.forEach((parsedEntity) => {\n let isChanged = false;\n\n parsedEntity.organizedIndexes.forEach((organizedIndex) => {\n if (!isChanged && !organizedIndexes.has(organizedIndex)) {\n isChanged = true;\n }\n\n organizedIndexes.add(organizedIndex);\n });\n\n if (isChanged) {\n nestedEntities.push(parsedEntity);\n }\n });\n\n return {\n entity,\n organizedIndexes,\n nestedEntities,\n };\n}\n\nfunction processEntity(\n entity: ApiMessageEntity,\n entityContent: TextPart,\n nestedEntityContent: TextPart[],\n highlight?: string,\n messageId?: number,\n isSimple?: boolean,\n) {\n const entityText = typeof entityContent === 'string' && entityContent;\n const renderedContent = nestedEntityContent.length ? nestedEntityContent : entityContent;\n\n function renderNestedMessagePart() {\n return renderMessagePart(\n renderedContent, highlight, undefined, undefined, isSimple,\n );\n }\n\n if (!entityText) {\n return renderNestedMessagePart();\n }\n\n if (isSimple) {\n const text = renderNestedMessagePart();\n if (entity.type === ApiMessageEntityTypes.Spoiler) {\n return {text};\n }\n return text;\n }\n\n switch (entity.type) {\n case ApiMessageEntityTypes.Bold:\n return {renderNestedMessagePart()};\n case ApiMessageEntityTypes.Blockquote:\n return
{renderNestedMessagePart()}
;\n case ApiMessageEntityTypes.BotCommand:\n return (\n \n {renderNestedMessagePart()}\n \n );\n case ApiMessageEntityTypes.Hashtag:\n return (\n \n {renderNestedMessagePart()}\n \n );\n case ApiMessageEntityTypes.Cashtag:\n return (\n \n {renderNestedMessagePart()}\n \n );\n case ApiMessageEntityTypes.Code:\n return (\n \n {renderNestedMessagePart()}\n \n );\n case ApiMessageEntityTypes.Email:\n return (\n \n {renderNestedMessagePart()}\n \n );\n case ApiMessageEntityTypes.Italic:\n return {renderNestedMessagePart()};\n case ApiMessageEntityTypes.MentionName:\n return (\n \n {renderNestedMessagePart()}\n \n );\n case ApiMessageEntityTypes.Mention:\n return (\n \n {renderNestedMessagePart()}\n \n );\n case ApiMessageEntityTypes.Phone:\n return (\n \n {renderNestedMessagePart()}\n \n );\n case ApiMessageEntityTypes.Pre:\n return
{renderNestedMessagePart()}
;\n case ApiMessageEntityTypes.Strike:\n return {renderNestedMessagePart()};\n case ApiMessageEntityTypes.TextUrl:\n case ApiMessageEntityTypes.Url:\n return (\n \n {renderNestedMessagePart()}\n
\n );\n case ApiMessageEntityTypes.Underline:\n return {renderNestedMessagePart()};\n case ApiMessageEntityTypes.Spoiler:\n return {renderNestedMessagePart()};\n default:\n return renderNestedMessagePart();\n }\n}\n\nfunction processEntityAsHtml(\n entity: ApiMessageEntity,\n entityContent: TextPart,\n nestedEntityContent: TextPart[],\n) {\n const rawEntityText = typeof entityContent === 'string' && entityContent;\n\n const renderedContent = nestedEntityContent.length\n ? nestedEntityContent.join('')\n : renderText(entityContent, ['escape_html', 'emoji_html', 'br_html']).join('');\n\n if (!rawEntityText) {\n return renderedContent;\n }\n\n switch (entity.type) {\n case ApiMessageEntityTypes.Bold:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Italic:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Underline:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Code:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Pre:\n return `\\`\\`\\`
${renderedContent}
\\`\\`\\``;\n case ApiMessageEntityTypes.Strike:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.MentionName:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Url:\n case ApiMessageEntityTypes.TextUrl:\n return `${renderedContent}`;\n case ApiMessageEntityTypes.Spoiler:\n return `${renderedContent}`;\n default:\n return renderedContent;\n }\n}\n\nfunction getLinkUrl(entityContent: string, entity: ApiMessageEntity) {\n const { type, url } = entity;\n return type === ApiMessageEntityTypes.TextUrl && url ? url : entityContent;\n}\n\nfunction handleBotCommandClick(e: MouseEvent) {\n getActions().sendBotCommand({ command: e.currentTarget.innerText });\n}\n\nfunction handleHashtagClick(e: MouseEvent) {\n getActions().setLocalTextSearchQuery({ query: e.currentTarget.innerText });\n getActions().searchTextMessagesLocal();\n}\n\nfunction handleCodeClick(e: MouseEvent) {\n copyTextToClipboard(e.currentTarget.innerText);\n getActions().showNotification({\n message: getTranslation('TextCopied'),\n });\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 { getActions, withGlobal } from '../../../global';\n\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport { selectUser } from '../../../global/selectors';\n\ntype OwnProps = {\n userId?: string;\n username?: string;\n children: React.ReactNode;\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 } = getActions();\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: React.ReactNode;\n size?: 'default' | 'smaller' | 'tiny';\n color?: (\n 'primary' | 'secondary' | 'gray' | 'danger' | 'translucent' | 'translucent-white' | 'translucent-black' | 'dark'\n );\n backgroundImage?: string;\n id?: string;\n className?: string;\n round?: boolean;\n pill?: boolean;\n fluid?: boolean;\n isText?: boolean;\n isLoading?: boolean;\n ariaLabel?: string;\n ariaControls?: string;\n hasPopup?: boolean;\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 id,\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 ariaControls,\n hasPopup,\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 id={id}\n className={fullClassName}\n href={href}\n title={ariaLabel}\n download={download}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n aria-label={ariaLabel}\n aria-controls={ariaControls}\n >\n {children}\n {!disabled && ripple && (\n \n )}\n \n );\n }\n\n return (\n }\n id={id}\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 aria-controls={ariaControls}\n aria-haspopup={hasPopup}\n title={ariaLabel}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\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 tabIndex?: number;\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 tabIndex,\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: React.ReactNode;\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 {\n ChangeEvent, FormEvent, RefObject,\n} 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 tabIndex?: 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 tabIndex,\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: React.ReactNode;\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';\nimport buildClassName from '../../util/buildClassName';\n\nimport './Loading.scss';\n\ntype OwnProps = {\n color?: 'blue' | 'white' | 'black' | 'yellow';\n backgroundColor?: 'light' | 'dark';\n onClick?: NoneToVoidFunction;\n};\n\nconst Loading: FC = ({ color = 'blue', backgroundColor, onClick }) => {\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';\nimport { IS_BACKDROP_BLUR_SUPPORTED, IS_COMPACT_MENU } from '../../util/environment';\n\nimport './Menu.scss';\n\ntype OwnProps = {\n ref?: RefObject;\n containerRef?: RefObject;\n isOpen: boolean;\n id?: string;\n className?: string;\n style?: string;\n bubbleStyle?: string;\n ariaLabelledBy?: string;\n transformOriginX?: number;\n transformOriginY?: number;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n autoClose?: boolean;\n shouldSkipTransition?: boolean;\n footer?: string;\n noCloseOnBackdrop?: boolean;\n noCompact?: 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: React.ReactNode;\n};\n\nconst ANIMATION_DURATION = 200;\n\nconst Menu: FC = ({\n ref,\n containerRef,\n isOpen,\n id,\n className,\n style,\n bubbleStyle,\n ariaLabelledBy,\n children,\n transformOriginX,\n transformOriginY,\n positionX = 'left',\n positionY = 'top',\n autoClose = false,\n footer,\n noCloseOnBackdrop = false,\n noCompact,\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 (isOpen || (!isOpen && prevIsOpen === true)) {\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 const transformOriginYStyle = transformOriginY !== undefined ? `${transformOriginY}px` : undefined;\n const transformOriginXStyle = transformOriginX !== undefined ? `${transformOriginX}px` : undefined;\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';\nimport { IS_COMPACT_MENU } from '../../util/environment';\n\nimport './MenuItem.scss';\n\ntype OnClickHandler = (e: React.SyntheticEvent) => void;\n\ntype OwnProps = {\n icon?: string;\n className?: string;\n children: React.ReactNode;\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 IS_COMPACT_MENU && 'compact',\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' | 'yellow';\n backgroundColor?: 'light' | 'dark';\n}> = ({\n color = 'blue',\n backgroundColor,\n}) => {\n return (\n
\n
\n
\n );\n};\n\nexport default Spinner;\n","export const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION!;\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 PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const DEBUG_PAYMENT_SMART_GLOCAL = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 500;\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 200;\nexport const GLOBAL_STATE_CACHE_CHATS_WITH_MESSAGES_LIMIT = 30;\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-v8';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const AUTODOWNLOAD_FILESIZE_MB_LIMITS = [1, 5, 10, 50, 100, 500];\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\nexport const GROUP_CALL_PARTICIPANTS_LIMIT = 100;\nexport const REACTION_LIST_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\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\nexport const CUSTOM_APPENDIX_ATTRIBUTE = 'data-has-custom-appendix';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const 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 = 100;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const STICKER_SIZE_JOIN_REQUESTS = 140;\nexport const STICKER_SIZE_INVITES = 140;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const NO_STICKER_SET_ID = 'NO_STICKER_SET';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\nexport const VIDEO_WEBM_TYPE = 'video/webm';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const 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\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 { addActionHandler, getActions, getGlobal } from '../../index';\n\nimport { initApi, callApi } from '../../../api/gramjs';\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, IS_WEBM_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\naddActionHandler('initApi', async (global, actions) => {\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 isWebmSupported: IS_WEBM_SUPPORTED,\n });\n});\n\naddActionHandler('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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('uploadProfilePhoto', (global, actions, payload) => {\n const { file } = payload!;\n\n void callApi('uploadProfilePhoto', file);\n});\n\naddActionHandler('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\naddActionHandler('returnToAuthPhoneNumber', (global) => {\n void callApi('restartAuth');\n\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddActionHandler('goToAuthQrCode', (global) => {\n void callApi('restartAuthWithQr');\n\n return {\n ...global,\n authIsLoadingQrCode: true,\n authError: undefined,\n };\n});\n\naddActionHandler('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\naddActionHandler('signOut', async (_global, _actions, payload) => {\n try {\n await unsubscribe();\n await callApi('destroy');\n await forceWebsync(false);\n } catch (err) {\n // Do nothing\n }\n\n getActions().reset();\n\n if (payload?.forceInitApi) {\n getActions().initApi();\n }\n});\n\naddActionHandler('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 getActions().init();\n});\n\naddActionHandler('disconnect', () => {\n void callApi('disconnect');\n});\n\naddActionHandler('loadNearestCountry', async (global) => {\n if (global.connectionState !== 'connectionStateReady') {\n return undefined;\n }\n\n const authNearestCountry = await callApi('fetchNearestCountry');\n\n return {\n ...getGlobal(),\n authNearestCountry,\n };\n});\n\naddActionHandler('setDeviceToken', (global, actions, deviceToken) => {\n return {\n ...global,\n push: {\n deviceToken,\n subscribedAt: Date.now(),\n },\n };\n});\n\naddActionHandler('deleteDeviceToken', (global) => {\n return {\n ...global,\n push: undefined,\n };\n});\n","import { addActionHandler, getGlobal, setGlobal } from '../../index';\n\nimport { GlobalState } from '../../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\naddActionHandler('updateProfile', async (global, actions, payload) => {\n const {\n photo, firstName, lastName, bio: about, username,\n } = payload!;\n\n const { currentUserId } = global;\n if (!currentUserId) {\n return undefined;\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 return {\n ...getGlobal(),\n profileEdit: {\n progress: ProfileEditProgress.Complete,\n },\n };\n});\n\naddActionHandler('checkUsername', async (global, actions, payload) => {\n const { username } = payload!;\n\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 undefined;\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 return {\n ...global,\n profileEdit: {\n ...global.profileEdit!,\n isUsernameAvailable,\n },\n };\n});\n\naddActionHandler('loadWallpapers', async () => {\n const result = await callApi('fetchWallpapers');\n if (!result) {\n return undefined;\n }\n\n const global = getGlobal();\n return {\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: result.wallpapers,\n },\n };\n});\n\naddActionHandler('uploadWallpaper', async (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 const result = await callApi('uploadWallpaper', file);\n if (!result) {\n return undefined;\n }\n\n const { wallpaper } = result;\n\n global = getGlobal();\n if (!global.settings.loadedWallpapers) {\n return undefined;\n }\n\n const firstWallpaper = global.settings.loadedWallpapers[0];\n if (!firstWallpaper || firstWallpaper.slug !== UPLOADING_WALLPAPER_SLUG) {\n return undefined;\n }\n\n const withLocalMedia = {\n ...wallpaper,\n document: {\n ...wallpaper.document,\n previewBlobUrl,\n },\n };\n\n return {\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: [\n withLocalMedia,\n ...global.settings.loadedWallpapers.slice(1),\n ],\n },\n };\n});\n\naddActionHandler('loadBlockedContacts', async (global) => {\n const result = await callApi('fetchBlockedContacts');\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n\n if (result.users?.length) {\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n }\n if (result.chats?.length) {\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n }\n\n global = {\n ...global,\n blocked: {\n ...global.blocked,\n ids: [...(global.blocked.ids || []), ...result.blockedIds],\n totalCount: result.totalCount,\n },\n };\n\n return global;\n});\n\naddActionHandler('blockContact', async (global, actions, payload) => {\n const { contactId, accessHash } = payload!;\n\n const result = await callApi('blockContact', contactId, accessHash);\n if (!result) {\n return undefined;\n }\n\n return addBlockedContact(getGlobal(), contactId);\n});\n\naddActionHandler('unblockContact', async (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 undefined;\n }\n\n accessHash = user.accessHash;\n }\n\n const result = await callApi('unblockContact', contactId, accessHash);\n if (!result) {\n return undefined;\n }\n\n return removeBlockedContact(getGlobal(), contactId);\n});\n\naddActionHandler('loadAuthorizations', async () => {\n const result = await callApi('fetchAuthorizations');\n if (!result) {\n return undefined;\n }\n\n return {\n ...getGlobal(),\n activeSessions: result,\n };\n});\n\naddActionHandler('terminateAuthorization', async (global, actions, payload) => {\n const { hash } = payload!;\n\n const result = await callApi('terminateAuthorization', hash);\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n\n return {\n ...global,\n activeSessions: global.activeSessions.filter((session) => session.hash !== hash),\n };\n});\n\naddActionHandler('terminateAllAuthorizations', async (global) => {\n const result = await callApi('terminateAllAuthorizations');\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n\n return {\n ...global,\n activeSessions: global.activeSessions.filter((session) => session.isCurrent),\n };\n});\n\naddActionHandler('loadNotificationExceptions', async (global) => {\n const { serverTimeOffset } = global;\n\n const result = await callApi('fetchNotificationExceptions', { serverTimeOffset });\n if (!result) {\n return undefined;\n }\n\n return addNotifyExceptions(getGlobal(), result);\n});\n\naddActionHandler('loadNotificationSettings', async (global) => {\n const { serverTimeOffset } = global;\n const result = await callApi('fetchNotificationSettings', {\n serverTimeOffset,\n });\n if (!result) {\n return undefined;\n }\n\n return replaceSettings(getGlobal(), result);\n});\n\naddActionHandler('updateNotificationSettings', async (global, actions, payload) => {\n const { peerType, isSilent, shouldShowPreviews } = payload!;\n\n const result = await callApi('updateNotificationSettings', peerType, { isSilent, shouldShowPreviews });\n if (!result) {\n return undefined;\n }\n\n return updateNotifySettings(getGlobal(), peerType, isSilent, shouldShowPreviews);\n});\n\naddActionHandler('updateWebNotificationSettings', (global, actions, payload) => {\n setGlobal(replaceSettings(global, payload));\n\n const { hasPushNotifications, hasWebNotifications } = global.settings.byKey;\n if (hasWebNotifications && hasPushNotifications) {\n void subscribe();\n } else {\n void unsubscribe();\n }\n});\n\naddActionHandler('updateContactSignUpNotification', async (global, actions, payload) => {\n const { isSilent } = payload!;\n\n const result = await callApi('updateContactSignUpNotification', isSilent);\n if (!result) {\n return undefined;\n }\n\n return replaceSettings(getGlobal(), { hasContactJoinedNotifications: !isSilent });\n});\n\naddActionHandler('loadLanguages', async () => {\n const result = await callApi('fetchLanguages');\n if (!result) {\n return undefined;\n }\n\n return replaceSettings(getGlobal(), { languages: result });\n});\n\naddActionHandler('loadPrivacySettings', async (global) => {\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 undefined;\n }\n\n 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 return global;\n});\n\naddActionHandler('setPrivacyVisibility', async (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 undefined;\n }\n\n const rules = buildInputPrivacyRules(global, {\n visibility,\n allowedIds: [...settings.allowUserIds, ...settings.allowChatIds],\n deniedIds: [...settings.blockUserIds, ...settings.blockChatIds],\n });\n\n const result = await callApi('setPrivacySettings', privacyKey, rules);\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n\n return {\n ...global,\n settings: {\n ...global.settings,\n privacy: {\n ...global.settings.privacy,\n [privacyKey]: result,\n },\n },\n };\n});\n\naddActionHandler('setPrivacySettings', async (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 undefined;\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 const result = await callApi('setPrivacySettings', privacyKey, rules);\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n\n return {\n ...global,\n settings: {\n ...global.settings,\n privacy: {\n ...global.settings.privacy,\n [privacyKey]: result,\n },\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\naddActionHandler('updateIsOnline', (global, actions, payload) => {\n callApi('updateIsOnline', payload);\n});\n\naddActionHandler('loadContentSettings', async () => {\n const result = await callApi('fetchContentSettings');\n if (!result) return undefined;\n\n return replaceSettings(getGlobal(), result);\n});\n\naddActionHandler('updateContentSettings', async (global, actions, payload) => {\n setGlobal(replaceSettings(getGlobal(), { isSensitiveEnabled: payload }));\n\n const result = await callApi('updateContentSettings', payload);\n if (!result) {\n return replaceSettings(getGlobal(), { isSensitiveEnabled: !payload });\n }\n\n return undefined;\n});\n\naddActionHandler('loadCountryList', async (global, actions, payload = {}) => {\n let { langCode } = payload;\n if (!langCode) langCode = global.settings.byKey.language;\n\n const countryList = await callApi('fetchCountryList', { langCode });\n if (!countryList) return undefined;\n\n return {\n ...getGlobal(),\n countryList,\n };\n});\n\naddActionHandler('ensureTimeFormat', async (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 if (global.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\naddActionHandler('loadAppConfig', async () => {\n const appConfig = await callApi('fetchAppConfig');\n if (!appConfig) return undefined;\n\n return {\n ...getGlobal(),\n appConfig,\n };\n});\n","import {\n addActionHandler, getActions, getGlobal, setGlobal,\n} from '../../index';\n\nimport { GlobalState } from '../../types';\n\nimport {\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\naddActionHandler('apiUpdate', (global, actions, update) => {\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 });\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 if (connectionState === global.connectionState) {\n return;\n }\n\n setGlobal({\n ...global,\n connectionState,\n });\n\n if (connectionState === 'connectionStateBroken') {\n // When mounting Auth `initApi` will be called from an effect. Otherwise, we force it here.\n const isOnAuth = !global.authState || [\n 'authorizationStateWaitPhoneNumber',\n 'authorizationStateWaitCode',\n 'authorizationStateWaitPassword',\n 'authorizationStateWaitRegistration',\n 'authorizationStateWaitQrCode',\n ].includes(global.authState);\n\n getActions().signOut({ forceInitApi: isOnAuth });\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 getActions().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 { addActionHandler, getGlobal, setGlobal } from '../../index';\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\naddActionHandler('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\naddActionHandler('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\naddActionHandler('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n return {\n ...global,\n authPhoneNumber: phoneNumber,\n };\n});\n\naddActionHandler('setAuthRememberMe', (global, actions, payload) => {\n return {\n ...global,\n authRememberMe: Boolean(payload),\n };\n});\n\naddActionHandler('clearAuthError', (global) => {\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddActionHandler('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 { addActionHandler } from '../../index';\nimport { ISettings, IThemeSettings, ThemeKey } from '../../../types';\nimport { replaceSettings, replaceThemeSettings } from '../../reducers';\n\naddActionHandler('setSettingOption', (global, actions, payload?: Partial) => {\n return replaceSettings(global, payload);\n});\n\naddActionHandler('setThemeSettings', (global, actions, payload: { theme: ThemeKey } & Partial) => {\n const { theme, ...settings } = payload;\n\n return replaceThemeSettings(global, theme, settings);\n});\n","import {\n ApiChat,\n ApiUser,\n ApiChatBannedRights,\n ApiChatAdminRights,\n ApiChatFolder,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { NotifyException, NotifySettings } from '../../types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport { ARCHIVED_FOLDER_ID, REPLIES_USER_ID } from '../../config';\nimport { orderBy } from '../../util/iteratees';\nimport { getUserFirstOrLastName } from './users';\nimport { formatDateToString, formatTime } from '../../util/dateFormat';\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(lang, untilDate * 1000)],\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 getFolderDescriptionText(lang: LangFn, folder: ApiChatFolder, chatsCount?: number) {\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 chatsCount !== undefined && (\n Object.values(filters).filter(Boolean).length > 1\n || (excludedChatIds?.length)\n || (includedChatIds?.length)\n )) {\n return lang('Chats', chatsCount);\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\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, ApiReactions, ApiUser,\n} from '../../api/types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport {\n CONTENT_NOT_SUPPORTED,\n LOCAL_MESSAGE_ID_BASE,\n RE_LINK_TEMPLATE,\n SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../config';\nimport { getUserFullName } from './users';\nimport { IS_OPUS_SUPPORTED, isWebpSupported } 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');\n\nexport type MessageKey = `msg${string}-${number}`;\n\nexport function getMessageHtmlId(messageId: number) {\n return `message${messageId.toString().replace('.', '-')}`;\n}\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 getMessageText(message: ApiMessage) {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact, invoice, location,\n } = message.content;\n\n if (text) {\n return text.text;\n }\n\n if (sticker || photo || video || audio || voice || document\n || contact || poll || webPage || invoice || location) {\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 Boolean(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 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.isLottie ? 'tgs' : content.sticker.isVideo\n ? 'webm' : 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\nexport function areReactionsEmpty(reactions: ApiReactions) {\n return !reactions.results.some((l) => l.count > 0);\n}\n\nexport function isGeoLiveExpired(message: ApiMessage, timestamp = Date.now() / 1000) {\n const { location } = message.content;\n if (location?.type !== 'geoLive') return false;\n return (timestamp - (message.date || 0) >= location.period);\n}\n","import { ApiMessage, ApiReactions } from '../../api/types';\n\nexport function getMessageRecentReaction(message: Partial) {\n return message.isOutgoing ? message.reactions?.recentReactions?.[0] : undefined;\n}\n\nexport function checkIfReactionAdded(oldReactions?: ApiReactions, newReactions?: ApiReactions, currentUserId?: string) {\n if (!oldReactions || !oldReactions.recentReactions) return true;\n if (!newReactions || !newReactions.recentReactions) return false;\n // Skip reactions from yourself\n if (newReactions.recentReactions.every((reaction) => reaction.userId === currentUserId)) return false;\n const oldReactionsMap = oldReactions.results.reduce>((acc, reaction) => {\n acc[reaction.reaction] = reaction.count;\n return acc;\n }, {});\n return newReactions.results.some((r) => !oldReactionsMap[r.reaction] || oldReactionsMap[r.reaction] < r.count);\n}\n","import { ApiMessage, ApiMessageEntityTypes } from '../../api/types';\nimport type { TextPart } from '../../components/common/helpers/renderTextWithEntities';\nimport { CONTENT_NOT_SUPPORTED } from '../../config';\n\nimport { LangFn } from '../../hooks/useLang';\nimport trimText from '../../util/trimText';\nimport { getMessageText } from './messages';\nimport { getMessageRecentReaction } from './reactions';\n\nconst SPOILER_CHARS = ['⠺', '⠵', '⠞', '⠟'];\nexport const TRUNCATED_SUMMARY_LENGTH = 80;\n\nexport function getMessageSummaryText(\n lang: LangFn,\n message: ApiMessage,\n noEmoji = false,\n truncateLength = TRUNCATED_SUMMARY_LENGTH,\n noReactions = true,\n isExtended = false,\n) {\n const emoji = !noEmoji && getMessageSummaryEmoji(message, noReactions);\n const emojiWithSpace = emoji ? `${emoji} ` : '';\n const text = trimText(getMessageTextWithSpoilers(message), truncateLength);\n const description = getMessageSummaryDescription(lang, message, text, noReactions, isExtended);\n\n return `${emojiWithSpace}${description}`;\n}\n\nexport function getMessageTextWithSpoilers(message: ApiMessage) {\n const text = getMessageText(message);\n if (!text) {\n return undefined;\n }\n\n const { entities } = message.content.text || {};\n if (!entities?.length) {\n return text;\n }\n\n return entities.reduce((accText, {\n type,\n offset,\n length,\n }) => {\n if (type !== ApiMessageEntityTypes.Spoiler) {\n return accText;\n }\n\n const spoiler = generateBrailleSpoiler(length);\n\n return `${accText.substr(0, offset)}${spoiler}${accText.substr(offset + length, accText.length)}`;\n }, text);\n}\n\nexport function getMessageSummaryEmoji(message: ApiMessage, noReactions = true) {\n const {\n photo,\n video,\n audio,\n voice,\n document,\n sticker,\n poll,\n } = message.content;\n\n if (message.groupedId || photo) {\n return '🖼';\n }\n\n if (video) {\n return '📹';\n }\n\n if (sticker) {\n return sticker.emoji;\n }\n\n if (audio) {\n return '🎧';\n }\n\n if (voice) {\n return '🎤';\n }\n\n if (document) {\n return '📎';\n }\n\n if (poll) {\n return '📊';\n }\n\n const reaction = !noReactions && getMessageRecentReaction(message);\n if (reaction) {\n return reaction.reaction;\n }\n\n return undefined;\n}\n\nexport function getMessageSummaryDescription(\n lang: LangFn,\n message: ApiMessage,\n truncatedText?: string | TextPart[],\n noReactions = true,\n isExtended = false,\n) {\n const {\n text,\n photo,\n video,\n audio,\n voice,\n document,\n sticker,\n contact,\n poll,\n invoice,\n location,\n } = message.content;\n\n let summary: string | TextPart[] | undefined;\n\n if (message.groupedId) {\n summary = truncatedText || lang('lng_in_dlg_album');\n }\n\n if (photo) {\n summary = truncatedText || lang('AttachPhoto');\n }\n\n if (video) {\n summary = truncatedText || lang(video.isGif ? 'AttachGif' : 'AttachVideo');\n }\n\n if (sticker) {\n summary = lang('AttachSticker').trim();\n }\n\n if (audio) {\n summary = getMessageAudioCaption(message) || lang('AttachMusic');\n }\n\n if (voice) {\n summary = truncatedText || lang('AttachAudio');\n }\n\n if (document) {\n summary = isExtended ? document.fileName : (truncatedText || document.fileName);\n }\n\n if (contact) {\n summary = lang('AttachContact');\n }\n\n if (poll) {\n summary = poll.summary.question;\n }\n\n if (invoice) {\n summary = `${lang('PaymentInvoice')}: ${invoice.text}`;\n }\n\n if (text) {\n if (isExtended && summary) {\n summary += `\\n${truncatedText}`;\n } else {\n summary = truncatedText;\n }\n }\n\n if (location?.type === 'geo' || location?.type === 'venue') {\n summary = lang('Message.Location');\n }\n\n if (location?.type === 'geoLive') {\n summary = lang('Message.LiveLocation');\n }\n\n const reaction = !noReactions && getMessageRecentReaction(message);\n if (summary && reaction) {\n summary = `to your \"${summary}\"`;\n }\n\n return summary || CONTENT_NOT_SUPPORTED;\n}\n\nexport function generateBrailleSpoiler(length: number) {\n return new Array(length)\n .fill(undefined)\n .map(() => SPOILER_CHARS[Math.floor(Math.random() * SPOILER_CHARS.length)])\n .join('');\n}\n\nfunction getMessageAudioCaption(message: ApiMessage) {\n const {\n audio,\n text,\n } = message.content;\n\n return (audio && [audio.title, audio.performer].filter(Boolean)\n .join(' — ')) || (text?.text);\n}\n","import {\n ApiAudio, ApiMediaFormat, ApiMessage, ApiMessageSearchType, ApiPhoto, ApiVideo, ApiDimensions, ApiLocation,\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 getMessageLocation(message: ApiMessage) {\n return message.content.location;\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 buildStaticMapHash(\n geo: ApiLocation['geo'],\n width: number,\n height: number,\n zoom: number,\n scale: number,\n) {\n const {\n long, lat, accessHash, accuracyRadius,\n } = geo;\n\n // eslint-disable-next-line max-len\n return `staticMap:${accessHash}?lat=${lat}&long=${long}&w=${width}&h=${height}&zoom=${zoom}&scale=${scale}&accuracyRadius=${accuracyRadius}`;\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 const content = messagePhoto || messageVideo || sticker || audio || voice || document;\n\n if (!content) {\n return undefined;\n }\n\n const mediaId = content.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): 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.isLottie) {\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 return getMessageContentIds(messages, listedIds, isFromSharedMedia ? 'media' : 'inlineMedia');\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(lang, wasOnlineDate));\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(lang, wasOnlineDate));\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(\n userIds: string[],\n usersById: Record,\n query?: string,\n currentUserId?: string,\n savedMessagesLang?: string,\n) {\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 = id === currentUserId ? savedMessagesLang : 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 { typify } from '../lib/teact/teactn';\nimport { GlobalState, ActionPayloads, NonTypedActionNames } from './types';\n\nconst typed = typify();\n\nexport const getGlobal = typed.getGlobal;\nexport const setGlobal = typed.setGlobal;\nexport const getActions = typed.getActions;\nexport const addActionHandler = typed.addActionHandler;\nexport const withGlobal = typed.withGlobal;\n","import { GlobalState } from '../types';\nimport { ApiChat, ApiChatMember, ApiPhoto } from '../../api/types';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { areSortedArraysEqual, 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\nexport function addChatMembers(global: GlobalState, chat: ApiChat, membersToAdd: ApiChatMember[]): GlobalState {\n const currentMembers = chat.fullInfo?.members;\n const newMemberIds = new Set(membersToAdd.map((m) => m.userId));\n const updatedMembers = [\n ...currentMembers?.filter((m) => !newMemberIds.has(m.userId)) || [],\n ...membersToAdd,\n ];\n const currentIds = currentMembers?.map(({ userId }) => userId) || [];\n const updatedIds = updatedMembers.map(({ userId }) => userId);\n\n if (areSortedArraysEqual(currentIds, updatedIds)) {\n return global;\n }\n\n return updateChat(global, chat.id, {\n fullInfo: {\n ...chat.fullInfo,\n members: updatedMembers,\n },\n });\n}\n","import { GlobalState } from '../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 const addedSets = global.stickers.added.setIds || [];\n let setIds: string[] = addedSets;\n if (update.installedDate && addedSets && !addedSets.includes(stickerSetId)) {\n setIds = [stickerSetId, ...setIds];\n }\n\n if (!update.installedDate && addedSets?.includes(stickerSetId)) {\n setIds = setIds.filter((id) => id !== stickerSetId);\n }\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n added: {\n ...global.stickers.added,\n setIds,\n },\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 '../types';\nimport { ApiUser, ApiUserStatus } from '../../api/types';\n\nimport { omit, pick } from '../../util/iteratees';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\nimport { updateChat } from './chats';\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 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 global = replaceUsers(global, {\n ...byId,\n [userId]: {\n ...byId[userId],\n isContact: undefined,\n },\n });\n\n return updateChat(global, userId, {\n settings: undefined,\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\nexport function closeNewContactDialog(global: GlobalState): GlobalState {\n return {\n ...global,\n newContact: undefined,\n };\n}\n","import { GlobalState } from '../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 '../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) => b - a);\n}\n","import { GlobalState } from '../types';\nimport { ManagementProgress, ManagementState } from '../../types';\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 '../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\n// eslint-disable-next-line consistent-return\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}\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 '../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 '../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 setSmartGlocalCardInfo(\n global: GlobalState,\n cardInfo: { type: string; token: string },\n): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n smartGlocalCredentials: {\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 setConfirmPaymentUrl(global: GlobalState, url?: string): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n confirmPaymentUrl: url,\n },\n };\n}\n\nexport function setReceipt(\n global: GlobalState,\n receipt?: ApiReceipt,\n message?: ApiMessage,\n): GlobalState {\n if (!receipt || !message) {\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n };\n }\n\n const { invoice: messageInvoice } = message.content;\n const { photoUrl, text, title } = (messageInvoice || {});\n\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: {\n ...receipt,\n photoUrl,\n text,\n title,\n },\n },\n };\n}\n\nexport function clearPayment(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {},\n };\n}\n\nexport function closeInvoice(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n isPaymentModalOpen: false,\n },\n };\n}\n","import { GlobalState } from '../types';\nimport { ApiChannelStatistics, ApiGroupStatistics, StatisticsGraph } from '../../api/types';\n\nexport function updateStatistics(\n global: GlobalState, chatId: string, statistics: ApiChannelStatistics | ApiGroupStatistics,\n): GlobalState {\n return {\n ...global,\n statistics: {\n byChatId: {\n ...global.statistics.byChatId,\n [chatId]: statistics,\n },\n },\n };\n}\n\nexport function updateStatisticsGraph(\n global: GlobalState, chatId: string, name: string, update: StatisticsGraph,\n): GlobalState {\n return {\n ...global,\n statistics: {\n byChatId: {\n ...global.statistics.byChatId,\n [chatId]: {\n ...(global.statistics.byChatId[chatId] || {}),\n [name]: update,\n },\n },\n },\n };\n}\n","import {\n GlobalState, MessageList, MessageListType, Thread,\n} from '../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\nexport function 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 { ApiChat, MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalState } from '../types';\n\nimport {\n getPrivateChatUserId, isChatChannel, isUserId, isHistoryClearMessage, isUserBot, isUserOnline,\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';\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 Boolean(active?.includes(chatId));\n }\n\n if (folderId === ARCHIVED_FOLDER_ID) {\n return Boolean(archived?.includes(chatId));\n }\n\n const { byId: chatFoldersById } = global.chatFolders;\n\n const { pinnedChatIds } = chatFoldersById[folderId] || {};\n return Boolean(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\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 '../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\n stickersForEmoji = stickersForEmoji.concat(packs[emoji] || [], packs[cleanEmoji(emoji)] || []);\n });\n return stickersForEmoji;\n}\n\nfunction cleanEmoji(emoji: string) {\n // Some emojis (❤️ for example) with a service symbol 'VARIATION SELECTOR-16' are not recognized as animated\n return emoji.replace('\\ufe0f', '');\n}\n\nexport function selectAnimatedEmoji(global: GlobalState, emoji: string) {\n const { animatedEmojis } = global;\n if (!animatedEmojis || !animatedEmojis.stickers) {\n return undefined;\n }\n\n const cleanedEmoji = cleanEmoji(emoji);\n\n return animatedEmojis.stickers.find((sticker) => sticker.emoji === emoji || sticker.emoji === cleanedEmoji);\n}\n\nexport function selectAnimatedEmojiEffect(global: GlobalState, emoji: string) {\n const { animatedEmojiEffects } = global;\n if (!animatedEmojiEffects || !animatedEmojiEffects.stickers) {\n return undefined;\n }\n\n const cleanedEmoji = cleanEmoji(emoji);\n\n return animatedEmojiEffects.stickers.find((sticker) => sticker.emoji === emoji || sticker.emoji === cleanedEmoji);\n}\n\nexport function selectAnimatedEmojiSound(global: GlobalState, emoji: string) {\n return global?.appConfig?.emojiSounds[cleanEmoji(emoji)];\n}\n\nexport function selectLocalAnimatedEmoji(global: GlobalState, emoji: string) {\n const cleanedEmoji = cleanEmoji(emoji);\n\n return cleanedEmoji === '🍑' ? 'Peach' : (cleanedEmoji === '🍆' ? 'Eggplant' : undefined);\n}\n\nexport function selectLocalAnimatedEmojiEffect(emoji: string) {\n return emoji === 'Eggplant' ? 'Cumshot' : undefined;\n}\n\nexport function selectLocalAnimatedEmojiEffectByName(name: string) {\n return name === 'Cumshot' ? '🍆' : undefined;\n}\n","import { GlobalState, MessageListType, Thread } from '../types';\nimport {\n ApiChat,\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { LOCAL_MESSAGE_ID_BASE, REPLIES_USER_ID, SERVICE_NOTIFICATIONS_USER_ID } from '../../config';\nimport {\n selectChat, selectChatBot, selectIsChatWithBot, selectIsChatWithSelf,\n} from './chats';\nimport { selectIsUserOrChatContact, selectUser, selectUserStatus } 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 selectEditingDraft(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'editingDraft');\n}\n\nexport function selectEditingScheduledId(global: GlobalState, chatId: string) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'editingScheduledId');\n}\n\nexport function selectEditingScheduledDraft(global: GlobalState, chatId: string) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'editingScheduledDraft');\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 selectIsMessageInCurrentMessageList(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) || content.location\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 canSaveGif = message.content.video?.isGif;\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 canSaveGif,\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 canSaveGif,\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\nexport function selectDefaultReaction(global: GlobalState, chatId: string) {\n if (chatId === SERVICE_NOTIFICATIONS_USER_ID) return undefined;\n\n const isPrivate = isUserId(chatId);\n const defaultReaction = global.appConfig?.defaultReaction;\n const { availableReactions } = global;\n if (!defaultReaction || !availableReactions?.some(\n (l) => l.reaction === defaultReaction && !l.isInactive,\n )) {\n return undefined;\n }\n\n if (isPrivate) {\n return defaultReaction;\n }\n\n const enabledReactions = selectChat(global, chatId)?.fullInfo?.enabledReactions;\n if (!enabledReactions?.includes(defaultReaction)) {\n return undefined;\n }\n\n return defaultReaction;\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectVisibleUsers(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const messageIds = selectThreadParam(global, chatId, threadId, 'viewportIds');\n if (!messageIds) {\n return undefined;\n }\n\n return messageIds.map((messageId) => {\n const { senderId } = selectChatMessage(global, chatId, messageId) || {};\n return senderId ? selectUser(global, senderId) : undefined;\n }).filter(Boolean);\n}\n\nexport function selectShouldSchedule(global: GlobalState) {\n return selectCurrentMessageList(global)?.type === 'scheduled';\n}\n\nexport function selectCanScheduleUntilOnline(global: GlobalState, id: string) {\n const isChatWithSelf = selectIsChatWithSelf(global, id);\n const chatBot = id === REPLIES_USER_ID && selectChatBot(global, id);\n return Boolean(\n !isChatWithSelf && !chatBot && isUserId(id) && selectUserStatus(global, id)?.wasOnline,\n );\n}\n","import { GlobalState } from '../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 selectCurrentMediaSearch(global: GlobalState) {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return undefined;\n }\n\n return global.localMediaSearch.byChatId[chatId];\n}\n","import { GlobalState } from '../types';\n\nimport { selectCurrentMessageList } from './messages';\nimport { selectChat } from './chats';\n\nexport function selectStatistics(global: GlobalState, chatId: string) {\n return global.statistics.byChatId[chatId];\n}\n\nexport function selectIsStatisticsShown(global: GlobalState) {\n if (!global.isStatisticsShown) {\n return false;\n }\n\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const chat = currentChatId ? selectChat(global, currentChatId) : undefined;\n\n return chat?.fullInfo?.canViewStatistics;\n}\n","import { GlobalState } from '../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 '../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 { selectIsStatisticsShown } from './statistics';\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 return selectIsPollResultsOpen(global) ? (\n RightColumnContent.PollResults\n ) : !IS_SINGLE_COLUMN_LAYOUT && selectCurrentTextSearch(global) ? (\n RightColumnContent.Search\n ) : selectCurrentManagement(global) ? (\n RightColumnContent.Management\n ) : selectIsStatisticsShown(global) ? (\n RightColumnContent.Statistics\n ) : selectCurrentStickerSearch(global).query !== undefined ? (\n RightColumnContent.StickerSearch\n ) : selectCurrentGifSearch(global).query !== undefined ? (\n RightColumnContent.GifSearch\n ) : global.newChatMembersProgress !== NewChatMembersProgress.Closed ? (\n RightColumnContent.AddingMembers\n ) : global.isChatInfoShown && selectCurrentMessageList(global) ? (\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 '../types';\n\nexport function selectCurrentGlobalSearchQuery(global: GlobalState) {\n return global.globalSearch.query;\n}\n","import { GlobalState } from '../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?.publishableKey;\n}\n\nexport function selectProviderPublicToken(global: GlobalState) {\n return global.payment.nativeParams?.publicToken;\n}\n\nexport function selectStripeCredentials(global: GlobalState) {\n return global.payment.stripeCredentials;\n}\n\nexport function selectSmartGlocalCredentials(global: GlobalState) {\n return global.payment.smartGlocalCredentials;\n}\n","import { GlobalState } from '../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 '../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\n// Slow, not to be used in `withGlobal`\nexport function selectUserByPhoneNumber(global: GlobalState, phoneNumber: string) {\n const phoneNumberCleaned = phoneNumber.replace(/[^0-9]/g, '');\n\n return Object.values(global.users.byId).find((user) => user?.phoneNumber === phoneNumberCleaned);\n}\n\nexport function selectIsUserOrChatContact(global: GlobalState, userOrChat: ApiUser | ApiChat) {\n return global.contactList && global.contactList.userIds.includes(userOrChat.id);\n}\n","import { useEffect } from '../lib/teact/teact';\nimport usePrevious from './usePrevious';\n\nconst useEffectWithPrevDeps = (\n cb: (args: T | readonly []) => void, dependencies: T, debugKey?: string,\n) => {\n const prevDeps = usePrevious(dependencies);\n return useEffect(() => {\n return cb(prevDeps || []);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies, debugKey);\n};\n\nexport default useEffectWithPrevDeps;\n","import { useCallback, useState } from '../lib/teact/teact';\n\nconst useFlag = (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\nexport default useFlag;\n","import { useCallback, useState } from '../lib/teact/teact';\n\nconst useForceUpdate = () => {\n const [, setTrigger] = useState(false);\n\n return useCallback(() => {\n setTrigger((trigger) => !trigger);\n }, []);\n};\n\nexport default useForceUpdate;\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\nconst useHeavyAnimationCheck = (\n handleAnimationStart: AnyToVoidFunction,\n handleAnimationEnd: AnyToVoidFunction,\n isDisabled = false,\n) => {\n useEffect(() => {\n if (isDisabled) {\n return undefined;\n }\n\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 }, [isDisabled, 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\nexport default useHeavyAnimationCheck;\n","import { useCallback, useEffect, useRef } from '../lib/teact/teact';\n\nimport { IS_IOS } from '../util/environment';\nimport usePrevious from './usePrevious';\nimport { getActions } from '../global';\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 getActions()\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 getActions()\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\nconst useKeyboardListNavigation = (\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\nexport default useKeyboardListNavigation;\n","import * as langProvider from '../util/langProvider';\nimport useForceUpdate from './useForceUpdate';\nimport useOnChange from './useOnChange';\n\nexport type LangFn = typeof langProvider.getTranslation;\n\nconst useLang = (): LangFn => {\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n return langProvider.addCallback(forceUpdate);\n }, [forceUpdate]);\n\n return langProvider.getTranslation;\n};\n\nexport default useLang;\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\nconst useModuleLoader = >(\n bundleName: B, moduleName: M, noLoad = false, autoUpdate = false,\n) => {\n const module = getModuleFromMemory(bundleName, moduleName);\n const forceUpdate = useForceUpdate();\n\n useEffect(() => {\n if (!autoUpdate) {\n return undefined;\n }\n\n return addLoadListener(forceUpdate);\n }, [autoUpdate, forceUpdate]);\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\nexport default useModuleLoader;\n","import usePrevious from './usePrevious';\n\nconst useOnChange = (cb: (args: T | readonly []) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n if (!prevDeps || dependencies.some((d, i) => d !== prevDeps[i])) {\n cb(prevDeps || []);\n }\n};\n\nexport default useOnChange;\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\nconst useShowTransition = (\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 const exec = () => {\n setIsClosed(true);\n\n if (onCloseTransitionEnd) {\n onCloseTransitionEnd();\n }\n\n closeTimeoutRef.current = undefined;\n };\n\n if (noCloseTransition) {\n exec();\n } else {\n closeTimeoutRef.current = window.setTimeout(exec, CLOSE_DURATION);\n }\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\nexport default useShowTransition;\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 VirtualElementChildren,\n} from './teact';\nimport generateIdFor from '../../util/generateIdFor';\nimport { DEBUG } from '../../config';\nimport { addEventListener, removeEventListener } from './dom-events';\nimport { unique } from '../../util/iteratees';\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 const isCurrentComponent = $current && isComponentElement($current);\n const isNewComponent = $new && isComponentElement($new);\n\n if (\n !skipComponentUpdate\n && isCurrentComponent && isNewComponent\n && !hasElementChanged($current!, $new!)\n ) {\n $new = updateComponent($current as VirtualElementComponent, $new as VirtualElementComponent);\n }\n\n // Parent element may have changed, so we need to update the listener closure.\n if (!skipComponentUpdate && isNewComponent && ($new as VirtualElementComponent).componentInstance.isMounted) {\n setupComponentUpdateListener($new as VirtualElementComponent, $parent, index, parentEl);\n }\n\n if ($current === $new) {\n return $new;\n }\n\n if (DEBUG && $new) {\n const newTarget = getTarget($new);\n if (newTarget && (!$current || newTarget !== getTarget($current))) {\n throw new Error('[Teact] Cached virtual element was moved within tree');\n }\n }\n\n if (!$current && $new) {\n if (isNewComponent) {\n $new = initComponent($new as VirtualElementComponent, $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 (isNewComponent) {\n $new = initComponent($new as VirtualElementComponent, $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 = isCurrentComponent && isNewComponent;\n const currentTarget = getTarget($current);\n\n if (!areComponents) {\n setTarget($new, currentTarget!);\n setTarget($current, undefined as any); // Help GC\n\n if ('props' in $current && 'props' in $new) {\n $new.props.ref = $current.props.ref;\n }\n }\n\n if (isRealElement($new)) {\n if (moveDirection) {\n const node = currentTarget!;\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 as VirtualRealElement), $new, currentTarget as HTMLElement);\n }\n\n $new.children = renderChildren(\n ($current as VirtualRealElement),\n $new,\n areComponents ? parentEl : currentTarget 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.entries(props).forEach(([key, value]) => {\n if (props[key] !== undefined) {\n setAttribute(element, key, value);\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 (DEBUG) {\n DEBUG_checkKeyUniqueness($new.children);\n }\n\n if ($new.props.teactFastList) {\n return renderFastListChildren($current, $new, currentEl);\n }\n\n const currentChildrenLength = $current.children.length;\n const newChildrenLength = $new.children.length;\n const maxLength = Math.max(currentChildrenLength, newChildrenLength);\n const newChildren = [];\n const fragment = newChildrenLength > currentChildrenLength + 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 >= currentChildrenLength ? { 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 moveDirection: shouldMoveNode ? (isMovingDown ? 'down' : 'up') : undefined,\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 currentEntries = Object.entries($current.props);\n const newEntries = Object.entries($new.props);\n\n currentEntries.forEach(([key, currentValue]) => {\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 newEntries.forEach(([key, newValue]) => {\n const currentValue = $current.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 if ((element as HTMLInputElement).value !== value) {\n (element as HTMLInputElement).value = value;\n }\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\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction DEBUG_checkKeyUniqueness(children: VirtualElementChildren) {\n const firstChild = children[0];\n if (firstChild && 'props' in firstChild && firstChild.props.key !== undefined) {\n const keys = children.reduce((acc: any[], child) => {\n if ('props' in child && child.props.key) {\n acc.push(child.props.key);\n }\n\n return acc;\n }, []);\n\n if (keys.length !== unique(keys).length) {\n throw new Error('[Teact] Children keys are not unique');\n }\n }\n}\n\nconst TeactDOM = { render };\nexport default TeactDOM;\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 { 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?: readonly 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;\nconst DEBUG_SILENT_RENDERS_FOR = new Set(['TeactMemoWrapper', 'TeactNContainer', 'Button', 'ListItem', 'MenuItem']);\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 (!DEBUG_SILENT_RENDERS_FOR.has(componentName)) {\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: any) {\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 (isComponentElement($element)) {\n unmountComponent($element.componentInstance);\n } else {\n if (isTagElement($element)) {\n if ($element.target) {\n removeAllDelegatedListeners($element.target as HTMLElement);\n }\n\n if ($element.props.ref) {\n $element.props.ref.current = undefined; // Help GC\n }\n }\n\n if ($element.target) {\n $element.target = undefined; // Help GC\n }\n\n if (!isRealElement($element)) {\n return;\n }\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 // We need to clean refs before running effect cleanups\n componentInstance.hooks.memos.byCursor.forEach((memoContainer) => {\n memoContainer.current = undefined;\n });\n\n componentInstance.hooks.effects.byCursor.forEach(({ cleanup }) => {\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err: any) {\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 componentInstance.hooks.effects.byCursor.forEach((hook) => {\n hook.cleanup = undefined;\n hook.effect = undefined as any;\n hook.dependencies = undefined;\n });\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = undefined;\n hook.nextValue = undefined;\n hook.setter = undefined as any;\n });\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n hook.dependencies = undefined as any;\n });\n\n componentInstance.hooks = undefined as any;\n componentInstance.$element = undefined as any;\n componentInstance.renderedValue = undefined;\n componentInstance.Component = undefined as any;\n componentInstance.props = undefined as any;\n componentInstance.forceUpdate = undefined;\n componentInstance.onUpdate = undefined;\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 const componentElement = $element.children[0];\n return componentElement ? getTarget(componentElement) : undefined;\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(): [T, StateHookSetter];\nexport function useState(initial: T): [T, StateHookSetter];\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?: readonly 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: any) {\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?: readonly any[], debugKey?: string) {\n return useLayoutEffectBase(fastRaf, fastRafPrimary, effect, dependencies, debugKey);\n}\n\nexport function useLayoutEffect(effect: () => Function | void, dependencies?: readonly 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, debugKey?: string) {\n return function TeactMemoWrapper(props: Props) {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => createElement(Component, props), Object.values(props), debugKey);\n } as T;\n}\n\n// We need to keep it here for JSX.\nconst Teact = {\n createElement,\n Fragment,\n};\n\nexport default Teact;\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 { handleError } from '../../util/handleError';\nimport { isHeavyAnimating } from '../../hooks/useHeavyAnimationCheck';\n\nexport default React;\n\ntype GlobalState = AnyLiteral;\ntype ActionNames = string;\ntype ActionPayload = any;\n\ninterface ActionOptions {\n forceOnHeavyAnimation?: boolean;\n // Workaround for iOS gesture history navigation\n forceSyncOnIOs?: boolean;\n}\n\ntype Actions = Record void>;\n\ntype ActionHandler = (\n global: GlobalState,\n actions: Actions,\n payload: any,\n) => GlobalState | void | Promise;\n\ntype MapStateToProps = ((global: GlobalState, ownProps: OwnProps) => AnyLiteral);\n\nlet currentGlobal = {} as GlobalState;\n\nconst actionHandlers: Record = {};\nconst callbacks: Function[] = [updateContainers];\nconst actions = {} as Actions;\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?: ActionOptions) {\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 getActions() {\n return actions;\n}\n\nfunction handleAction(name: string, payload?: ActionPayload, options?: ActionOptions) {\n actionHandlers[name]?.forEach((handler) => {\n const response = handler(currentGlobal, actions, payload);\n if (!response) {\n return;\n }\n\n if (typeof response.then === 'function') {\n response.then((newGlobal: GlobalState | void) => {\n if (newGlobal) {\n setGlobal(newGlobal, options);\n }\n });\n } else {\n setGlobal(response, options);\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: any) {\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 addActionHandler(name: ActionNames, handler: ActionHandler) {\n if (!actionHandlers[name]) {\n actionHandlers[name] = [];\n\n actions[name] = (payload?: ActionPayload, options?: ActionOptions) => {\n handleAction(name, payload, options);\n };\n }\n\n actionHandlers[name].push(handler);\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: any) {\n handleError(err);\n }\n }\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ;\n };\n };\n}\n\nexport function typify() {\n type NonTypedActionPayloads = {\n [ActionName in NonTypedActionNames]: ActionPayload;\n };\n\n type ProjectActionTypes =\n ActionPayloads\n & NonTypedActionPayloads;\n\n type ProjectActionNames = keyof ProjectActionTypes;\n\n type ProjectActions = {\n [ActionName in ProjectActionNames]: (\n payload?: ProjectActionTypes[ActionName],\n options?: ActionOptions,\n ) => void;\n };\n\n type ActionHandlers = {\n [ActionName in keyof ProjectActionTypes]: (\n global: ProjectGlobalState,\n actions: ProjectActions,\n payload: ProjectActionTypes[ActionName],\n ) => ProjectGlobalState | void | Promise;\n };\n\n return {\n getGlobal: getGlobal as () => ProjectGlobalState,\n setGlobal: setGlobal as (state: ProjectGlobalState, options?: ActionOptions) => void,\n getActions: getActions as () => ProjectActions,\n addActionHandler: addActionHandler as (\n name: ActionName,\n handler: ActionHandlers[ActionName],\n ) => void,\n withGlobal: withGlobal as (\n mapStateToProps: ((global: ProjectGlobalState, ownProps: OwnProps) => AnyLiteral),\n ) => (Component: FC) => FC,\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 ApiBotInlineMediaResult, ApiBotInlineResult, ApiBotInlineSwitchPm,\n ApiChatInviteImporter,\n ApiExportedInvite,\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 isConnectionStatusMinimized: 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 QuickReaction,\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 Search,\n Management,\n Statistics,\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 interface ManagementState {\n isActive: boolean;\n nextScreen?: ManagementScreens;\n isUsernameAvailable?: boolean;\n error?: string;\n invites?: ApiExportedInvite[];\n revokedInvites?: ApiExportedInvite[];\n editingInvite?: ApiExportedInvite;\n inviteInfo?: {\n invite: ApiExportedInvite;\n importers?: ApiChatInviteImporter[];\n requesters?: ApiChatInviteImporter[];\n };\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 ConfirmPayment,\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 ChannelRemovedUsers,\n GroupUserPermissionsCreate,\n GroupUserPermissions,\n ChatAdministrators,\n GroupRecentActions,\n ChatAdminRights,\n ChatNewAdminRights,\n GroupMembers,\n GroupAddAdmins,\n Invites,\n EditInvite,\n Reactions,\n InviteInfo,\n JoinRequests,\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 if (!instance!.isCancelled && tick()) {\n fastRaf(() => {\n animateSingle(tick, instance);\n });\n }\n}\n\nexport function animate(tick: Function) {\n if (tick()) {\n fastRaf(() => {\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)[];\ntype PartsWithGlobals = (string | false | undefined | string[])[];\ntype ClassNameBuilder =\n ((elementName: string, ...modifiers: PartsWithGlobals) => string)\n & Record;\n\nexport default function buildClassName(...parts: Parts) {\n return parts.filter(Boolean).join(' ');\n}\n\nexport function createClassNameBuilder(componentName: string) {\n return ((elementName: string, ...modifiers: PartsWithGlobals) => {\n const baseName = elementName === '&' ? componentName : `${componentName}__${elementName}`;\n\n return modifiers.reduce((acc, modifier) => {\n if (modifier) {\n // A bit hacky way to pass global class names\n if (Array.isArray(modifier)) {\n acc.push(...modifier);\n } else {\n acc.push(`${baseName}--${modifier}`);\n }\n }\n\n return acc;\n }, [baseName]).join(' ');\n }) as ClassNameBuilder;\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 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","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 function hasCallbacks() {\n return Boolean(callbacks.length);\n }\n\n return {\n runCallbacks,\n addCallback,\n removeCallback,\n hasCallbacks,\n };\n}\n\nexport type CallbackManager = ReturnType;\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 { DEBUG } from '../config';\n\nexport const CLIPBOARD_ITEM_SUPPORTED = window.navigator.clipboard && window.ClipboardItem;\n\nconst textCopyEl = document.createElement('textarea');\ntextCopyEl.setAttribute('readonly', '');\ntextCopyEl.tabIndex = -1;\ntextCopyEl.className = 'visually-hidden';\n\nexport const copyTextToClipboard = (str: string): void => {\n textCopyEl.value = str;\n document.body.appendChild(textCopyEl);\n const selection = document.getSelection();\n\n if (selection) {\n // Store previous selection\n const rangeToRestore = selection.rangeCount > 0 && selection.getRangeAt(0);\n textCopyEl.select();\n document.execCommand('copy');\n // Restore the original selection\n if (rangeToRestore) {\n selection.removeAllRanges();\n selection.addRange(rangeToRestore);\n }\n }\n\n document.body.removeChild(textCopyEl);\n};\n\nexport const copyImageToClipboard = (imageUrl?: string) => {\n if (!imageUrl) return;\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n const imageEl = new Image();\n imageEl.onload = (e: Event) => {\n if (ctx && e.currentTarget) {\n const img = e.currentTarget as HTMLImageElement;\n canvas.width = img.width;\n canvas.height = img.height;\n ctx.drawImage(img, 0, 0, img.width, img.height);\n canvas.toBlob(copyBlobToClipboard, 'image/png', 1);\n }\n };\n\n imageEl.src = imageUrl;\n};\n\nasync function copyBlobToClipboard(pngBlob: Blob | null) {\n if (!pngBlob || !CLIPBOARD_ITEM_SUPPORTED) {\n return;\n }\n\n try {\n await window.navigator.clipboard.write?.([\n new ClipboardItem({\n [pngBlob.type]: pngBlob,\n }),\n ]);\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n }\n}\n","import { LangFn } from '../hooks/useLang';\nimport withCache from './withCache';\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 isToday(date: Date) {\n return getDayStartAt(new Date()) === getDayStartAt(date);\n}\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(lang: LangFn, datetime: number | Date) {\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(lang, date);\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 formatCountdown(\n lang: LangFn,\n msLeft: number,\n) {\n const days = Math.floor(msLeft / MILLISECONDS_IN_DAY);\n if (msLeft < 0) {\n return 0;\n } else if (days < 1) {\n return formatMediaDuration(msLeft / 1000);\n } else if (days < 7) {\n return lang('Days', days);\n } else if (days < 30) {\n return lang('Weeks', Math.floor(days / 7));\n } else if (days < 365) {\n return lang('Months', Math.floor(days / 30));\n } else {\n return lang('Years', Math.floor(days / 365));\n }\n}\n\nexport function formatCountdownShort(lang: LangFn, msLeft: number) {\n if (msLeft < 60 * 1000) {\n return Math.ceil(msLeft / 1000);\n } else if (msLeft < 60 * 60 * 1000) {\n return Math.ceil(msLeft / (60 * 1000));\n } else if (msLeft < MILLISECONDS_IN_DAY) {\n return lang('MessageTimer.ShortHours', Math.ceil(msLeft / (60 * 60 * 1000)));\n } else {\n return lang('MessageTimer.ShortDays', Math.ceil(msLeft / MILLISECONDS_IN_DAY));\n }\n}\n\nexport function formatLastUpdated(lang: LangFn, currentTime: number, lastUpdated = currentTime) {\n const seconds = currentTime - lastUpdated;\n if (seconds < 60) {\n return lang('LiveLocationUpdated.JustNow');\n } else if (seconds < 60 * 60) {\n return lang('LiveLocationUpdated.MinutesAgo', Math.floor(seconds / 60));\n } else {\n return lang('LiveLocationUpdated.TodayAt', formatTime(lang, lastUpdated));\n }\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(lang, date)}`;\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\nconst formatDayToStringWithCache = withCache((dayStartAt: number, locale: string) => {\n return new Date(dayStartAt).toLocaleString(\n locale,\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n },\n );\n});\n\nexport function formatDateToString(datetime: Date | number, locale = 'en-US') {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const dayStartAt = getDayStartAt(date);\n\n return formatDayToStringWithCache(dayStartAt, locale);\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 window.navigator.mediaDevices && 'getUserMedia' in window.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');\n// `canPlayType(VIDEO_MOV_TYPE)` returns false negative at least for macOS Chrome and iOS Safari\nexport const IS_MOV_SUPPORTED = true;\n\nif (IS_MOV_SUPPORTED) SUPPORTED_VIDEO_CONTENT_TYPES.add(VIDEO_MOV_TYPE);\n\nexport const IS_WEBM_SUPPORTED = Boolean(TEST_VIDEO.canPlayType('video/webm; codecs=\"vp9\"').replace('no', ''))\n && !(IS_MAC_OS && IS_SAFARI); // Safari on MacOS has some issues with WebM\n\nexport const DPR = window.devicePixelRatio || 1;\n\nexport const MASK_IMAGE_DISABLED = true;\n\nexport const IS_BACKDROP_BLUR_SUPPORTED = !IS_TEST && (\n CSS.supports('backdrop-filter: blur()') || CSS.supports('-webkit-backdrop-filter: blur()')\n);\nexport const IS_COMPACT_MENU = !IS_TOUCH_ENV;\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 { addCallback } from '../lib/teact/teactn';\nimport { addActionHandler, getGlobal } from '../global';\n\nimport { GlobalState } from '../global/types';\nimport { NotifyException, NotifySettings } from '../types';\nimport { ApiChat, ApiChatFolder, ApiUser } from '../api/types';\n\nimport { ALL_FOLDER_ID, ARCHIVED_FOLDER_ID, DEBUG } from '../config';\nimport { selectNotifySettings, selectNotifyExceptions } from '../global/selectors';\nimport { selectIsChatMuted } from '../global/helpers';\nimport { onIdle, throttle } from './schedulers';\nimport { areSortedArraysEqual, unique } from './iteratees';\nimport arePropsShallowEqual from './arePropsShallowEqual';\nimport { CallbackManager, createCallbackManager } from './callbacks';\n\ninterface FolderSummary {\n id: number;\n listIds?: Set;\n orderedPinnedIds?: string[];\n contacts?: true;\n nonContacts?: true;\n groups?: true;\n channels?: true;\n bots?: true;\n excludeMuted?: true;\n excludeRead?: true;\n excludeArchived?: true;\n excludedChatIds?: Set;\n includedChatIds?: Set;\n pinnedChatIds?: Set;\n}\n\ninterface ChatSummary {\n id: string;\n type: ApiChat['type'];\n isListed: boolean;\n isArchived: boolean;\n isMuted: boolean;\n isUnread: boolean;\n unreadCount?: number;\n unreadMentionsCount?: number;\n order: number;\n isUserBot?: boolean;\n isUserContact?: boolean;\n}\n\nconst UPDATE_THROTTLE = 500;\nconst DEBUG_DURATION_LIMIT = 6;\n\nconst initials = buildInitials();\n\nlet prevGlobal: {\n allFolderListIds?: GlobalState['chats']['listIds']['active'];\n allFolderPinnedIds?: GlobalState['chats']['orderedPinnedIds']['active'];\n archivedFolderListIds?: GlobalState['chats']['listIds']['archived'];\n archivedFolderPinnedIds?: GlobalState['chats']['orderedPinnedIds']['archived'];\n isAllFolderFullyLoaded?: boolean;\n isArchivedFolderFullyLoaded?: boolean;\n chatsById: Record;\n foldersById: Record;\n usersById: Record;\n notifySettings: NotifySettings;\n notifyExceptions?: Record;\n} = initials.prevGlobal;\n\nlet prepared: {\n folderSummariesById: Record;\n chatSummariesById: Map;\n folderIdsByChatId: Record;\n chatIdsByFolderId: Record | undefined>;\n isOrderedListJustPatched: Record;\n} = initials.prepared;\n\nlet results: {\n orderedIdsByFolderId: Record;\n pinnedCountByFolderId: Record; // Also watched by `callbacks.orderedIdsByFolderId`\n chatsCountByFolderId: Record;\n unreadCountersByFolderId: Record;\n} = initials.results;\n\nlet callbacks: {\n orderedIdsByFolderId: Record;\n chatsCountByFolderId: CallbackManager;\n unreadCountersByFolderId: CallbackManager;\n} = initials.callbacks;\n\nconst updateFolderManagerThrottled = throttle(() => {\n onIdle(() => {\n updateFolderManager(getGlobal());\n });\n}, UPDATE_THROTTLE);\n\nlet inited = false;\n\n/* Getters */\n\nexport function init() {\n inited = true;\n\n addCallback(updateFolderManagerThrottled);\n addActionHandler('reset', reset);\n\n updateFolderManager(getGlobal());\n}\n\nexport function getOrderedIds(folderId: number) {\n if (!inited) init();\n\n return results.orderedIdsByFolderId[folderId];\n}\n\nexport function getPinnedChatsCount(folderId: number) {\n if (!inited) init();\n\n return results.pinnedCountByFolderId[folderId] || 0;\n}\n\nexport function getChatsCount() {\n if (!inited) init();\n\n return results.chatsCountByFolderId;\n}\n\nexport function getUnreadCounters() {\n if (!inited) init();\n\n return results.unreadCountersByFolderId;\n}\n\nexport function getAllNotificationsCount() {\n return getUnreadCounters()[ALL_FOLDER_ID]?.notificationsCount || 0;\n}\n\n/* Callback managers */\n\nexport function addOrderedIdsCallback(folderId: number, callback: (orderedIds: string[]) => void) {\n if (!callbacks.orderedIdsByFolderId[folderId]) {\n callbacks.orderedIdsByFolderId[folderId] = createCallbackManager();\n }\n\n return callbacks.orderedIdsByFolderId[folderId].addCallback(callback);\n}\n\nexport function addChatsCountCallback(callback: (chatsCount: typeof results.chatsCountByFolderId) => void) {\n return callbacks.chatsCountByFolderId.addCallback(callback);\n}\n\nexport function addUnreadCountersCallback(callback: (unreadCounters: typeof results.unreadCountersByFolderId) => void) {\n return callbacks.unreadCountersByFolderId.addCallback(callback);\n}\n\n/* Global update handlers */\n\nfunction updateFolderManager(global: GlobalState) {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n let DEBUG_startedAt: number;\n if (DEBUG) {\n DEBUG_startedAt = performance.now();\n }\n\n const isAllFolderChanged = Boolean(\n global.chats.listIds.active\n && isMainFolderChanged(ALL_FOLDER_ID, global.chats.listIds.active, global.chats.orderedPinnedIds.active),\n );\n const isArchivedFolderChanged = Boolean(\n global.chats.listIds.archived\n && isMainFolderChanged(ARCHIVED_FOLDER_ID, global.chats.listIds.archived, global.chats.orderedPinnedIds.archived),\n );\n const isAllFullyLoadedChanged = global.chats.isFullyLoaded.active !== prevGlobal.isAllFolderFullyLoaded;\n const isArchivedFullyLoadedChanged = global.chats.isFullyLoaded.archived !== prevGlobal.isArchivedFolderFullyLoaded;\n\n const areFoldersChanged = global.chatFolders.byId !== prevGlobal.foldersById;\n const areChatsChanged = global.chats.byId !== prevGlobal.chatsById;\n const areUsersChanged = global.users.byId !== prevGlobal.usersById;\n const areNotifySettingsChanged = selectNotifySettings(global) !== prevGlobal.notifySettings;\n const areNotifyExceptionsChanged = selectNotifyExceptions(global) !== prevGlobal.notifyExceptions;\n\n let affectedFolderIds: number[] = [];\n\n if (isAllFullyLoadedChanged || isArchivedFullyLoadedChanged) {\n affectedFolderIds = affectedFolderIds.concat(\n updateFullyLoaded(global, isArchivedFullyLoadedChanged),\n );\n }\n\n if (!(\n isAllFolderChanged || isArchivedFolderChanged || areFoldersChanged\n || areChatsChanged || areUsersChanged || areNotifySettingsChanged || areNotifyExceptionsChanged\n )\n ) {\n if (affectedFolderIds.length) {\n updateResults(affectedFolderIds);\n }\n\n return;\n }\n\n const prevAllFolderListIds = prevGlobal.allFolderListIds;\n const prevArchivedFolderListIds = prevGlobal.archivedFolderListIds;\n\n updateFolders(global, isAllFolderChanged, isArchivedFolderChanged, areFoldersChanged);\n\n affectedFolderIds = affectedFolderIds.concat(updateChats(\n global,\n areFoldersChanged || isAllFolderChanged || isArchivedFolderChanged,\n areNotifySettingsChanged,\n areNotifyExceptionsChanged,\n prevAllFolderListIds,\n prevArchivedFolderListIds,\n ));\n\n updateResults(unique(affectedFolderIds));\n\n if (DEBUG) {\n const duration = performance.now() - DEBUG_startedAt!;\n if (duration > DEBUG_DURATION_LIMIT) {\n // eslint-disable-next-line no-console\n console.warn(`Slow \\`updateFolderManager\\`: ${Math.round(duration)} ms`);\n }\n }\n}\n\nfunction isMainFolderChanged(folderId: number, newListIds?: string[], newPinnedIds?: string[]) {\n const currentListIds = folderId === ALL_FOLDER_ID\n ? prevGlobal.allFolderListIds\n : prevGlobal.archivedFolderListIds;\n const currentPinnedIds = folderId === ALL_FOLDER_ID\n ? prevGlobal.allFolderPinnedIds\n : prevGlobal.archivedFolderPinnedIds;\n\n return currentListIds !== newListIds || currentPinnedIds !== newPinnedIds;\n}\n\nfunction updateFullyLoaded(\n global: GlobalState,\n isArchivedFullyLoadedChanged = false,\n) {\n let affectedFolderIds = [];\n\n if (isArchivedFullyLoadedChanged) {\n affectedFolderIds.push(ARCHIVED_FOLDER_ID);\n }\n\n const isAllFolderFullyLoaded = global.chats.isFullyLoaded.active;\n const isArchivedFolderFullyLoaded = global.chats.isFullyLoaded.archived;\n\n if (isAllFolderFullyLoaded && isArchivedFolderFullyLoaded) {\n const emptyFolderIds = Object.keys(prepared.folderSummariesById)\n .filter((folderId) => !results.orderedIdsByFolderId[folderId])\n .map(Number);\n\n affectedFolderIds = affectedFolderIds.concat(emptyFolderIds);\n }\n\n prevGlobal.isAllFolderFullyLoaded = isAllFolderFullyLoaded;\n prevGlobal.isArchivedFolderFullyLoaded = isArchivedFolderFullyLoaded;\n\n return affectedFolderIds;\n}\n\nfunction updateFolders(\n global: GlobalState, isAllFolderChanged: boolean, isArchivedFolderChanged: boolean, areFoldersChanged: boolean,\n) {\n const changedFolders = [];\n\n if (isAllFolderChanged) {\n const newListIds = global.chats.listIds.active!;\n const newPinnedIds = global.chats.orderedPinnedIds.active;\n\n prepared.folderSummariesById[ALL_FOLDER_ID] = buildFolderSummaryFromMainList(\n ALL_FOLDER_ID, newListIds, newPinnedIds,\n );\n\n prevGlobal.allFolderListIds = newListIds;\n prevGlobal.allFolderPinnedIds = newPinnedIds;\n\n changedFolders.push(ALL_FOLDER_ID);\n }\n\n if (isArchivedFolderChanged) {\n const newListIds = global.chats.listIds.archived!;\n const newPinnedIds = global.chats.orderedPinnedIds.archived;\n\n prepared.folderSummariesById[ARCHIVED_FOLDER_ID] = buildFolderSummaryFromMainList(\n ARCHIVED_FOLDER_ID, newListIds, newPinnedIds,\n );\n\n prevGlobal.archivedFolderListIds = newListIds;\n prevGlobal.archivedFolderPinnedIds = newPinnedIds;\n\n changedFolders.push(ARCHIVED_FOLDER_ID);\n }\n\n if (areFoldersChanged) {\n const newFoldersById = global.chatFolders.byId;\n\n Object.values(newFoldersById).forEach((folder) => {\n if (folder === prevGlobal.foldersById[folder.id]) {\n return;\n }\n\n prepared.folderSummariesById[folder.id] = buildFolderSummary(folder);\n\n changedFolders.push(folder.id);\n });\n\n prevGlobal.foldersById = newFoldersById;\n }\n\n return changedFolders;\n}\n\nfunction buildFolderSummaryFromMainList(\n folderId: number, listIds: string[], orderedPinnedIds?: string[],\n): FolderSummary {\n return {\n id: folderId,\n listIds: new Set(listIds),\n orderedPinnedIds,\n pinnedChatIds: new Set(orderedPinnedIds),\n };\n}\n\nfunction buildFolderSummary(folder: ApiChatFolder): FolderSummary {\n return {\n ...folder,\n orderedPinnedIds: folder.pinnedChatIds,\n excludedChatIds: folder.excludedChatIds ? new Set(folder.excludedChatIds) : undefined,\n includedChatIds: folder.excludedChatIds ? new Set(folder.includedChatIds) : undefined,\n pinnedChatIds: folder.excludedChatIds ? new Set(folder.pinnedChatIds) : undefined,\n };\n}\n\nfunction updateChats(\n global: GlobalState,\n areFoldersChanged: boolean,\n areNotifySettingsChanged: boolean,\n areNotifyExceptionsChanged: boolean,\n prevAllFolderListIds?: string[],\n prevArchivedFolderListIds?: string[],\n) {\n const newChatsById = global.chats.byId;\n const newUsersById = global.users.byId;\n const newNotifySettings = selectNotifySettings(global);\n const newNotifyExceptions = selectNotifyExceptions(global);\n const folderSummaries = Object.values(prepared.folderSummariesById);\n const affectedFolderIds = new Set();\n\n const newAllFolderListIds = global.chats.listIds.active;\n const newArchivedFolderListIds = global.chats.listIds.archived;\n let allIds = [...newAllFolderListIds || [], ...newArchivedFolderListIds || []];\n if (newAllFolderListIds !== prevAllFolderListIds || newArchivedFolderListIds !== prevArchivedFolderListIds) {\n allIds = unique(allIds.concat(prevAllFolderListIds || [], prevArchivedFolderListIds || []));\n }\n\n allIds.forEach((chatId) => {\n const chat = newChatsById[chatId];\n\n if (\n !areFoldersChanged\n && !areNotifySettingsChanged\n && !areNotifyExceptionsChanged\n && chat === prevGlobal.chatsById[chatId]\n && newUsersById[chatId] === prevGlobal.usersById[chatId]\n ) {\n return;\n }\n\n let newFolderIds: number[];\n if (chat) {\n const currentSummary = prepared.chatSummariesById.get(chatId);\n const newSummary = buildChatSummary(chat, newNotifySettings, newNotifyExceptions, newUsersById[chatId]);\n if (!areFoldersChanged && currentSummary && arePropsShallowEqual(newSummary, currentSummary)) {\n return;\n }\n\n prepared.chatSummariesById.set(chatId, newSummary);\n\n newFolderIds = buildChatFolderIds(newSummary, folderSummaries);\n newFolderIds.forEach((folderId) => {\n affectedFolderIds.add(folderId);\n });\n } else {\n prepared.chatSummariesById.delete(chatId);\n newFolderIds = [];\n }\n\n const currentFolderIds = prepared.folderIdsByChatId[chatId] || [];\n if (areSortedArraysEqual(newFolderIds, currentFolderIds)) {\n return;\n }\n\n const deletedFolderIds = updateListsForChat(chatId, currentFolderIds, newFolderIds);\n deletedFolderIds.forEach((folderId) => {\n affectedFolderIds.add(folderId);\n });\n });\n\n prevGlobal.chatsById = newChatsById;\n prevGlobal.usersById = newUsersById;\n prevGlobal.notifySettings = newNotifySettings;\n prevGlobal.notifyExceptions = newNotifyExceptions;\n\n return Array.from(affectedFolderIds);\n}\n\nfunction buildChatSummary(\n chat: ApiChat,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n user?: ApiUser,\n): ChatSummary {\n const {\n id, type, lastMessage, isRestricted, isNotJoined, folderId,\n unreadCount, unreadMentionsCount, hasUnreadMark,\n joinDate, draftDate,\n } = chat;\n\n const userInfo = type === 'chatTypePrivate' && user;\n\n return {\n id,\n type,\n isListed: Boolean(lastMessage && !isRestricted && !isNotJoined),\n isArchived: folderId === ARCHIVED_FOLDER_ID,\n isMuted: selectIsChatMuted(chat, notifySettings, notifyExceptions),\n isUnread: Boolean(unreadCount || unreadMentionsCount || hasUnreadMark),\n unreadCount,\n unreadMentionsCount,\n order: Math.max(joinDate || 0, draftDate || 0, lastMessage?.date || 0),\n isUserBot: userInfo ? userInfo.type === 'userTypeBot' : undefined,\n isUserContact: userInfo ? userInfo.isContact : undefined,\n };\n}\n\nfunction buildChatFolderIds(chatSummary: ChatSummary, folderSummaries: FolderSummary[]) {\n return folderSummaries.reduce((acc, folderSummary) => {\n if (isChatInFolder(chatSummary, folderSummary)) {\n acc.push(folderSummary.id);\n }\n\n return acc;\n }, []).sort();\n}\n\nfunction isChatInFolder(\n chatSummary: ChatSummary,\n folderSummary: FolderSummary,\n) {\n if (!chatSummary.isListed) {\n return false;\n }\n\n const { id: chatId, type } = chatSummary;\n\n if (folderSummary.listIds) {\n if (\n (chatSummary.isArchived && folderSummary.id === ALL_FOLDER_ID)\n || (!chatSummary.isArchived && folderSummary.id === ARCHIVED_FOLDER_ID)\n ) {\n return false;\n }\n\n return folderSummary.listIds.has(chatId);\n }\n\n if (folderSummary.excludedChatIds?.has(chatId)) {\n return false;\n }\n\n if (folderSummary.includedChatIds?.has(chatId)) {\n return true;\n }\n\n if (folderSummary.pinnedChatIds?.has(chatId)) {\n return true;\n }\n\n if (folderSummary.excludeArchived && chatSummary.isArchived) {\n return false;\n }\n\n if (folderSummary.excludeRead && !chatSummary.isUnread) {\n return false;\n }\n\n if (folderSummary.excludeMuted && chatSummary.isMuted && !chatSummary.unreadMentionsCount) {\n return false;\n }\n\n if (type === 'chatTypePrivate') {\n if (chatSummary.isUserBot) {\n if (folderSummary.bots) {\n return true;\n }\n } else {\n if (folderSummary.contacts && chatSummary.isUserContact) {\n return true;\n }\n\n if (folderSummary.nonContacts && !chatSummary.isUserContact) {\n return true;\n }\n }\n } else if (type === 'chatTypeChannel') {\n return Boolean(folderSummary.channels);\n } else if (type === 'chatTypeBasicGroup' || type === 'chatTypeSuperGroup') {\n return Boolean(folderSummary.groups);\n }\n\n return false;\n}\n\nfunction updateListsForChat(chatId: string, currentFolderIds: number[], newFolderIds: number[]) {\n const currentFolderIdsSet = new Set(currentFolderIds);\n const newFolderIdsSet = new Set(newFolderIds);\n const deletedFolderIds: number[] = [];\n\n unique([...currentFolderIds, ...newFolderIds]).forEach((folderId) => {\n let currentFolderOrderedIds = results.orderedIdsByFolderId[folderId];\n\n if (currentFolderIdsSet.has(folderId) && !newFolderIdsSet.has(folderId)) {\n prepared.chatIdsByFolderId[folderId]!.delete(chatId);\n\n deletedFolderIds.push(folderId);\n\n if (currentFolderOrderedIds) {\n currentFolderOrderedIds = currentFolderOrderedIds.filter((id) => id !== chatId);\n prepared.isOrderedListJustPatched[folderId] = true;\n }\n } else if (!currentFolderIdsSet.has(folderId) && newFolderIdsSet.has(folderId)) {\n if (!prepared.chatIdsByFolderId[folderId]) {\n prepared.chatIdsByFolderId[folderId] = new Set();\n }\n\n prepared.chatIdsByFolderId[folderId]!.add(chatId);\n\n if (currentFolderOrderedIds) {\n currentFolderOrderedIds.push(chatId);\n prepared.isOrderedListJustPatched[folderId] = true;\n }\n }\n\n results.orderedIdsByFolderId[folderId] = currentFolderOrderedIds;\n });\n\n prepared.folderIdsByChatId[chatId] = newFolderIds;\n\n return deletedFolderIds;\n}\n\nfunction updateResults(affectedFolderIds: number[]) {\n let wasUnreadCountersChanged = false;\n let wasChatsCountChanged = false;\n\n Array.from(affectedFolderIds).forEach((folderId) => {\n const { pinnedCount: newPinnedCount, orderedIds: newOrderedIds } = buildFolderOrderedIds(folderId);\n // When signed out\n if (!newOrderedIds) {\n return;\n }\n\n const currentOrderedIds = results.orderedIdsByFolderId[folderId];\n const currentPinnedCount = results.pinnedCountByFolderId[folderId];\n const areOrderedIdsChanged = (\n !currentOrderedIds\n || currentPinnedCount === undefined || currentPinnedCount !== newPinnedCount\n || prepared.isOrderedListJustPatched[folderId]\n || !areSortedArraysEqual(newOrderedIds, currentOrderedIds)\n );\n if (areOrderedIdsChanged) {\n prepared.isOrderedListJustPatched[folderId] = false;\n results.orderedIdsByFolderId[folderId] = newOrderedIds;\n results.pinnedCountByFolderId[folderId] = newPinnedCount;\n callbacks.orderedIdsByFolderId[folderId]?.runCallbacks(newOrderedIds);\n }\n\n const currentChatsCount = results.chatsCountByFolderId[folderId];\n const newChatsCount = newOrderedIds.length;\n if (!wasChatsCountChanged) {\n wasChatsCountChanged = currentChatsCount !== newChatsCount;\n }\n results.chatsCountByFolderId[folderId] = newChatsCount;\n\n const currentUnreadCounters = results.unreadCountersByFolderId[folderId];\n const newUnreadCounters = buildFolderUnreadCounters(folderId);\n if (!wasUnreadCountersChanged) {\n wasUnreadCountersChanged = (\n !currentUnreadCounters || !arePropsShallowEqual(newUnreadCounters, currentUnreadCounters)\n );\n }\n results.unreadCountersByFolderId[folderId] = newUnreadCounters;\n });\n\n if (wasChatsCountChanged) {\n // We need to update the entire object as it will be returned from a hook\n const newValue = { ...results.chatsCountByFolderId };\n results.chatsCountByFolderId = newValue;\n callbacks.chatsCountByFolderId.runCallbacks(newValue);\n }\n\n if (wasUnreadCountersChanged) {\n // We need to update the entire object as it will be returned from a hook\n const newValue = { ...results.unreadCountersByFolderId };\n results.unreadCountersByFolderId = newValue;\n callbacks.unreadCountersByFolderId.runCallbacks(newValue);\n }\n}\n\nfunction buildFolderOrderedIds(folderId: number) {\n const folderSummary = prepared.folderSummariesById[folderId];\n if (!folderSummary) {\n return {};\n }\n\n const { orderedPinnedIds, pinnedChatIds } = folderSummary;\n const {\n chatSummariesById,\n chatIdsByFolderId: { [folderId]: chatIds },\n } = prepared;\n const {\n orderedIdsByFolderId: { [folderId]: prevOrderedIds },\n } = results;\n\n const sortedPinnedIds = chatIds ? orderedPinnedIds?.filter((id) => chatIds.has(id)) : orderedPinnedIds;\n const allListIds = prevOrderedIds || (chatIds && Array.from(chatIds)) || [];\n const notPinnedIds = pinnedChatIds ? allListIds.filter((id) => !pinnedChatIds.has(id)) : allListIds;\n const sortedNotPinnedIds = notPinnedIds.sort((chatId1: string, chatId2: string) => {\n return chatSummariesById.get(chatId2)!.order - chatSummariesById.get(chatId1)!.order;\n });\n\n return {\n pinnedCount: sortedPinnedIds?.length || 0,\n orderedIds: [\n ...(sortedPinnedIds || []),\n ...sortedNotPinnedIds,\n ],\n };\n}\n\nfunction buildFolderUnreadCounters(folderId: number) {\n const {\n chatSummariesById,\n } = prepared;\n const {\n orderedIdsByFolderId: { [folderId]: orderedIds },\n } = results;\n\n return orderedIds!.reduce((newUnreadCounters, chatId) => {\n const chatSummary = chatSummariesById.get(chatId);\n if (!chatSummary) {\n return newUnreadCounters;\n }\n\n if (chatSummary.isUnread) {\n newUnreadCounters.chatsCount++;\n\n if (chatSummary.unreadMentionsCount) {\n newUnreadCounters.notificationsCount += chatSummary.unreadMentionsCount;\n }\n\n if (!chatSummary.isMuted) {\n if (chatSummary.unreadCount) {\n newUnreadCounters.notificationsCount += chatSummary.unreadCount;\n } else if (!chatSummary.unreadMentionsCount) {\n newUnreadCounters.notificationsCount += 1; // Manually marked unread\n }\n }\n }\n\n return newUnreadCounters;\n }, {\n chatsCount: 0,\n notificationsCount: 0,\n });\n}\n\nfunction buildInitials() {\n return {\n prevGlobal: {\n foldersById: {},\n chatsById: {},\n usersById: {},\n notifySettings: {} as NotifySettings,\n notifyExceptions: {},\n },\n\n prepared: {\n folderSummariesById: {},\n chatSummariesById: new Map(),\n folderIdsByChatId: {},\n chatIdsByFolderId: {},\n isOrderedListJustPatched: {},\n },\n\n results: {\n orderedIdsByFolderId: {},\n pinnedCountByFolderId: {},\n chatsCountByFolderId: {},\n unreadCountersByFolderId: {},\n },\n\n callbacks: {\n orderedIdsByFolderId: {},\n chatsCountByFolderId: createCallbackManager(),\n unreadCountersByFolderId: createCallbackManager(),\n },\n };\n}\n\nfunction reset() {\n const newInitials = buildInitials();\n\n prevGlobal = newInitials.prevGlobal;\n prepared = newInitials.prepared;\n results = newInitials.results;\n callbacks = newInitials.callbacks;\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","const generateIdFor = (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\nexport default generateIdFor;\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 // eslint-disable-next-line max-len\n SERVICE_WORKER_DISABLED: 'Service Worker is disabled. Streaming media may not be supported. Try reloading 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 BOT_PRECHECKOUT_TIMEOUT: 'The request for payment has expired',\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 // https://stackoverflow.com/questions/49384120/resizeobserver-loop-limit-exceeded\n if (e instanceof ErrorEvent && e.message === 'ResizeObserver loop limit exceeded') {\n return;\n }\n\n e.preventDefault();\n\n handleError(e instanceof ErrorEvent ? (e.error || e.message) : 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: T[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(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 '../global';\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","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 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.Blob,\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 ApiPreparedMedia;\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: Exclude): 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';\nimport { createCallbackManager } from './callbacks';\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\nconst { addCallback, runCallbacks } = createCallbackManager();\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(runCallbacks);\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\nexport const addLoadListener = addCallback;\n","import { callApi } from '../api/gramjs';\nimport {\n ApiChat, ApiMediaFormat, ApiMessage, ApiUser, ApiUserReaction,\n} from '../api/types';\nimport { renderActionMessageText } from '../components/common/helpers/renderActionMessageText';\nimport { DEBUG, IS_TEST } from '../config';\nimport { getActions, getGlobal, setGlobal } from '../global';\nimport {\n getChatAvatarHash,\n getChatTitle,\n getMessageAction,\n getMessageRecentReaction,\n getMessageSenderName,\n getMessageSummaryText,\n getPrivateChatUserId,\n isActionMessage,\n isChatChannel,\n selectIsChatMuted,\n selectShouldShowMessagePreview,\n} from '../global/helpers';\nimport { addNotifyExceptions, replaceSettings } from '../global/reducers';\nimport {\n selectChatMessage,\n selectCurrentMessageList,\n selectNotifyExceptions,\n selectNotifySettings,\n selectUser,\n} from '../global/selectors';\nimport { IS_SERVICE_WORKER_SUPPORTED, IS_TOUCH_ENV } from './environment';\nimport { getTranslation } from './langProvider';\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 = getActions();\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 getActions()\n .setDeviceToken(deviceToken);\n } catch (error: any) {\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 // On touch devices show notifications when chat is not active\n if (IS_TOUCH_ENV) {\n const {\n chatId,\n type,\n } = selectCurrentMessageList(global) || {};\n return !(chatId === chat.id && type === 'thread');\n }\n // On desktop show notifications when window is not focused\n return !document.hasFocus();\n}\n\nfunction getNotificationContent(chat: ApiChat, message: ApiMessage, reaction?: ApiUserReaction) {\n const global = getGlobal();\n const {\n replyToMessageId,\n } = message;\n let {\n senderId,\n } = message;\n if (reaction) senderId = reaction.userId;\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 isChat = chat && (isChatChannel(chat) || message.senderId === message.chatId);\n\n body = renderActionMessageText(\n getTranslation,\n message,\n !isChat ? messageSender : undefined,\n isChat ? chat : undefined,\n actionTargetUsers,\n actionTargetMessage,\n actionTargetChatId,\n { asPlainText: true },\n ) as string;\n } else {\n const senderName = getMessageSenderName(getTranslation, chat.id, messageSender);\n const summary = getMessageSummaryText(getTranslation, message, false, 60, false);\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 notifyAboutMessage({\n chat,\n message,\n isReaction = false,\n}: { chat: ApiChat; message: Partial; isReaction?: boolean }) {\n const { hasWebNotifications } = await loadNotificationSettings();\n if (!checkIfShouldNotify(chat)) return;\n const areNotificationsSupported = checkIfNotificationsSupported();\n if (!hasWebNotifications || !areNotificationsSupported) {\n // Do not play notification sound for reactions if web notifications are disabled\n if (isReaction) return;\n // Only play sound if web notifications are disabled\n playNotifySoundDebounced(String(message.id) || chat.id);\n return;\n }\n if (!areNotificationsSupported) return;\n\n if (!message.id) return;\n\n const activeReaction = getMessageRecentReaction(message);\n const icon = await getAvatar(chat);\n\n const {\n title,\n body,\n } = getNotificationContent(chat, message as ApiMessage, activeReaction);\n\n if (checkIfPushSupported()) {\n if (navigator.serviceWorker?.controller) {\n // notify service worker about new message notification\n navigator.serviceWorker.controller.postMessage({\n type: 'showMessageNotification',\n payload: {\n title,\n body,\n icon,\n chatId: chat.id,\n messageId: message.id,\n reaction: activeReaction?.reaction,\n },\n });\n }\n } else {\n const dispatch = getActions();\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 (activeReaction) {\n dispatch.startActiveReaction({\n messageId: message.id,\n reaction: activeReaction.reaction,\n });\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\nimport { LOCATION_HASH } from '../hooks/useHistoryBack';\n\nexport function createMessageHash(messageList: MessageList) {\n const typeOrThreadId = messageList.type !== 'thread' ? (\n `_${messageList.type}`\n ) : messageList.threadId !== -1 ? (\n `_${messageList.threadId}`\n ) : '';\n\n return `${messageList.chatId}${typeOrThreadId}`;\n}\n\nexport function parseLocationHash() {\n if (!LOCATION_HASH) return undefined;\n\n const [chatId, typeOrThreadId] = LOCATION_HASH.replace(/^#/, '').split('_');\n if (!chatId?.match(/^-?\\d+$/)) return undefined;\n\n const isType = ['thread', 'pinned', 'scheduled'].includes(typeOrThreadId);\n\n return {\n chatId,\n type: Boolean(typeOrThreadId) && isType ? (typeOrThreadId as MessageListType) : 'thread',\n threadId: Boolean(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 = /[^\\p{L}\\p{M}]+/ui;\n} catch (e) {\n // Support for older versions of firefox\n RE_NOT_LETTER = /[^\\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 * Delete multiple keys at once.\n *\n * @param keys List of keys to delete.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction delMany(keys, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n keys.forEach((key) => 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(store, callback) {\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 * 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 return customStore('readonly', (store) => {\n // Fast path for modern browsers\n if (store.getAllKeys) {\n return promisifyRequest(store.getAllKeys());\n }\n const items = [];\n return eachCursor(store, (cursor) => items.push(cursor.key)).then(() => items);\n });\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 return customStore('readonly', (store) => {\n // Fast path for modern browsers\n if (store.getAll) {\n return promisifyRequest(store.getAll());\n }\n const items = [];\n return eachCursor(store, (cursor) => items.push(cursor.value)).then(() => items);\n });\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 return customStore('readonly', (store) => {\n // Fast path for modern browsers\n // (although, hopefully we'll get a simpler path some day)\n if (store.getAll && store.getAllKeys) {\n return Promise.all([\n promisifyRequest(store.getAllKeys()),\n promisifyRequest(store.getAll()),\n ]).then(([keys, values]) => keys.map((key, i) => [key, values[i]]));\n }\n const items = [];\n return customStore('readonly', (store) => eachCursor(store, (cursor) => items.push([cursor.key, cursor.value])).then(() => items));\n });\n}\n\nexport { clear, createStore, del, delMany, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","/**\n * Work around Safari 14 IndexedDB open bug.\n *\n * Safari has a horrible bug where IDB requests can hang while the browser is starting up. https://bugs.webkit.org/show_bug.cgi?id=226547\n * The only solution is to keep nudging it until it's awake.\n */\nfunction idbReady() {\n var 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 var intervalId;\n return new Promise(function (resolve) {\n var tryIdb = function () { return indexedDB.databases().finally(resolve); };\n intervalId = setInterval(tryIdb, 100);\n tryIdb();\n }).finally(function () { return 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';\nimport { fastRaf } from './schedulers';\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\nconst switchTheme = (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 fastRaf(() => {\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 });\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\nexport default switchTheme;\n","import EMOJI_REGEX from '../lib/twemojiRegex';\nimport { fixNonStandardEmoji } from './emoji';\nimport withCache from './withCache';\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 const getFirstLetters = withCache((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","export default function trimText(text: T, length?: number) {\n if (!text || !length || text.length <= length) {\n return text;\n }\n\n return `${text.substring(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 '../global';\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 = () => Boolean(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\nexport function clearWebsync() {\n localStorage.removeItem(WEBSYNC_KEY);\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 currentWindowSize = updateSizes();\nlet isRefreshDisabled = false;\n\nfunction disableRefresh() {\n isRefreshDisabled = true;\n}\n\nfunction enableRefresh() {\n isRefreshDisabled = false;\n}\n\nconst handleResize = throttle(() => {\n currentWindowSize = 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 currentWindowSize.width <= MOBILE_SCREEN_MAX_WIDTH || (\n currentWindowSize.width <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH\n && currentWindowSize.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\nconst windowSize = {\n get: () => currentWindowSize,\n getIsKeyboardVisible: () => initialHeight > currentWindowSize.height,\n disableRefresh,\n enableRefresh,\n};\n\nexport default windowSize;\n","const cache = new WeakMap>();\n\nexport default function withCache(fn: T) {\n return (...args: Parameters): ReturnType => {\n let fnCache = cache.get(fn);\n const cacheKey = args.map(String).join('_');\n\n if (fnCache) {\n const cached = fnCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n } else {\n fnCache = new Map();\n cache.set(fn, fnCache);\n }\n\n const newValue = fn(...args);\n\n fnCache.set(cacheKey, newValue);\n\n return newValue;\n };\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 + \".\" + {\"13\":\"1cb726dfb0fe77ff16db\",\"99\":\"a19f6cfb125132c4ae9e\",\"133\":\"e050778acd78ac17365a\",\"161\":\"e3dd8735bd9f827bebc6\",\"354\":\"a5e899b2a69f227670ec\",\"395\":\"368d08862d9c65a1cf98\",\"472\":\"38e2fa9338b8e031169b\",\"501\":\"17afb8957510497ebb61\",\"524\":\"f47aff24c24945077d39\",\"536\":\"51c4121ec6034fff4884\",\"616\":\"421a1d053cdd90ce3d23\",\"654\":\"229871d7a07987919e6c\",\"742\":\"b2feed9283c594eb9e2f\",\"745\":\"7f9b9b63ef7b71c5b2d7\",\"878\":\"ba2ac4194b79d543b70f\",\"888\":\"3bcf93fb3c92294b2737\",\"915\":\"7c6d5a7308348c57bbbd\",\"941\":\"1399f916762c873a48a2\",\"970\":\"81d005f8fdd6b7e03eb7\",\"993\":\"c7c8681e7135da951723\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"\" + chunkId + \".\" + {\"13\":\"1cb726dfb0fe77ff16db\",\"133\":\"e050778acd78ac17365a\",\"395\":\"368d08862d9c65a1cf98\",\"472\":\"38e2fa9338b8e031169b\",\"616\":\"421a1d053cdd90ce3d23\",\"654\":\"229871d7a07987919e6c\",\"878\":\"ba2ac4194b79d543b70f\"}[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[chunkId] = 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 { getActions } from '../global';\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 = getActions();\n const payload = action.payload;\n switch (action.type) {\n case 'focusMessage':\n if (dispatch.focusMessage) {\n dispatch.focusMessage(payload);\n }\n if (dispatch.startActiveReaction && payload.reaction) {\n dispatch.startActiveReaction({\n messageId: payload.messageId,\n reaction: payload.reaction,\n });\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 if (!navigator.serviceWorker.controller) {\n const registrations = await navigator.serviceWorker.getRegistrations();\n if (registrations.length) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] Hard reload detected, re-enabling Service Worker');\n }\n await Promise.all(registrations.map((r) => r.unregister()));\n }\n }\n\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 getActions().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 volume: DEFAULT_VOLUME,\n playbackRate: DEFAULT_PLAYBACK_RATE,\n isMuted: false,\n },\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 isConnectionStatusMinimized: true,\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 activeReactions: {},\n\n shouldShowContextMenuHint: true,\n\n activeDownloads: {\n byChatId: {},\n },\n\n serviceNotifications: [],\n\n statistics: {\n byChatId: {},\n },\n};\n","import { addCallback, removeCallback } from '../lib/teact/teactn';\n\nimport { addActionHandler, getGlobal } from './index';\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_USER_LIST_LIMIT,\n GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT,\n GLOBAL_STATE_CACHE_CHATS_WITH_MESSAGES_LIMIT,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n DEFAULT_VOLUME,\n DEFAULT_PLAYBACK_RATE,\n ALL_FOLDER_ID,\n ARCHIVED_FOLDER_ID,\n} from '../config';\nimport { IS_SINGLE_COLUMN_LAYOUT } from '../util/environment';\nimport { isHeavyAnimating } from '../hooks/useHeavyAnimationCheck';\nimport { pick, unique } from '../util/iteratees';\nimport {\n selectCurrentChat,\n selectCurrentMessageList,\n selectVisibleUsers,\n} from './selectors';\nimport { hasStoredSession } from '../util/sessions';\nimport { INITIAL_STATE } from './initialState';\nimport { parseLocationHash } from '../util/routing';\nimport { isUserId } from './helpers';\nimport { getOrderedIds } from '../util/folderManager';\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 addActionHandler('saveSession', () => {\n if (isCaching) {\n return;\n }\n\n setupCaching();\n });\n\n addActionHandler('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() : 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 // Migrate from legacy setting names\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 // Pre-fill settings with defaults\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.mediaViewer.volume === undefined) {\n cached.mediaViewer.volume = DEFAULT_VOLUME;\n }\n\n if (cached.mediaViewer.playbackRate === undefined) {\n cached.mediaViewer.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 if (!cached.activeReactions) {\n cached.activeReactions = {};\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 mediaViewer: {\n volume: global.mediaViewer.volume,\n playbackRate: global.mediaViewer.playbackRate,\n isMuted: global.mediaViewer.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 availableReactions: reduceAvailableReactions(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 }, currentUserId } = global;\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const visibleUserIds = selectVisibleUsers(global)?.map(({ id }) => id);\n\n const idsToSave = unique([\n ...currentUserId ? [currentUserId] : [],\n ...currentChatId && isUserId(currentChatId) ? [currentChatId] : [],\n ...visibleUserIds || [],\n ...global.topPeers.userIds || [],\n ...getOrderedIds(ALL_FOLDER_ID)?.filter(isUserId) || [],\n ...getOrderedIds(ARCHIVED_FOLDER_ID)?.filter(isUserId) || [],\n ...global.contactList?.userIds || [],\n ...global.globalSearch.recentlyFoundChatIds?.filter(isUserId) || [],\n ...Object.keys(byId),\n ]).slice(0, GLOBAL_STATE_CACHE_USER_LIST_LIMIT);\n\n return {\n byId: pick(byId, idsToSave),\n statusesById: pick(statusesById, idsToSave),\n };\n}\n\nfunction reduceChats(global: GlobalState): GlobalState['chats'] {\n const { chats: { byId }, currentUserId } = global;\n const currentChat = selectCurrentChat(global);\n const idsToSave = unique([\n ...currentUserId ? [currentUserId] : [],\n ...currentChat ? [currentChat.id] : [],\n ...getOrderedIds(ALL_FOLDER_ID) || [],\n ...getOrderedIds(ARCHIVED_FOLDER_ID) || [],\n ...global.globalSearch.recentlyFoundChatIds || [],\n ...Object.keys(byId),\n ]).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT);\n\n return {\n ...global.chats,\n isFullyLoaded: {},\n byId: pick(global.chats.byId, idsToSave),\n };\n}\n\nfunction reduceMessages(global: GlobalState): GlobalState['messages'] {\n const { currentUserId } = global;\n const byChatId: GlobalState['messages']['byChatId'] = {};\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const chatIdsToSave = [\n ...currentChatId ? [currentChatId] : [],\n ...currentUserId ? [currentUserId] : [],\n ...getOrderedIds(ALL_FOLDER_ID)?.slice(0, GLOBAL_STATE_CACHE_CHATS_WITH_MESSAGES_LIMIT) || [],\n ];\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\nfunction reduceAvailableReactions(global: GlobalState): GlobalState['availableReactions'] {\n return global.availableReactions\n ?.map((r) => pick(r, ['reaction', 'staticIcon', 'title', 'isInactive']));\n}\n","import { addActionHandler } from './index';\n\nimport { INITIAL_STATE } from './initialState';\nimport { initCache, loadCache } from './cache';\nimport { cloneDeep } from '../util/iteratees';\n\ninitCache();\n\naddActionHandler('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 { getActions, getGlobal, withGlobal } from '../../global';\n\nimport { ApiMediaFormat } from '../../api/types';\nimport { GlobalState } from '../../global/types';\n\nimport { getChatAvatarHash } from '../../global/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\nimport telegramLogoPath from '../../assets/telegram-logo.svg';\nimport reactionThumbsPath from '../../assets/reaction-thumbs.png';\nimport monkeyPath from '../../assets/monkey.svg';\nimport { selectIsRightColumnShown, selectTheme } from '../../global/selectors';\n\ntype OwnProps = {\n page: 'main' | 'authCode' | 'authPassword' | 'authPhoneNumber' | 'authQrCode';\n children: React.ReactNode;\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 preloadImage(reactionThumbsPath),\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 } = getActions();\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\nconst useLangString = (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\nexport default useLangString;\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 '../../global';\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 }> = useCallback(({ 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 }, [filter, handleInput, handleInputKeyDown, id, isLoading, lang, value]);\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\nimport monkeyPath from '../../assets/monkey.svg';\n\nimport React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getActions, withGlobal } from '../../global';\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 } = getActions();\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 } = getActions();\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.QR2.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 { getActions, withGlobal } from '../../global';\n\nimport { GlobalState } from '../../global/types';\n\nimport '../../global/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 } = getActions();\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 React, { FC, useEffect } from './lib/teact/teact';\nimport { getActions, withGlobal } from './global';\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 } = getActions();\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 from './lib/teact/teact';\nimport TeactDOM from './lib/teact/teact-dom';\n\nimport { getActions, getGlobal } from './global';\nimport './global/init';\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\ngetActions().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","ensureWorkerPing","setTimeout","makeRequest","args","callApi","fnName","warn","promise","name","err","cancelApiProgress","progressCallback","isCanceled","postMessage","generateIdFor","payload","Promise","Object","assign","pop","set","catch","finally","delete","startedAt","Date","now","async","race","pause","then","location","reload","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","getActions","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","openChat","id","Link","focusMessage","handleMessageClick","chatId","groupCall","joinGroupCall","accessHash","MAX_LENGTH","NBSP","renderActionMessageText","lang","actionOriginUser","actionOriginChat","targetUsers","targetMessage","targetChatId","options","action","translationValues","amount","currency","call","noLinks","asPlainText","asTextWithSpoilers","translationKey","processed","unprocessed","undefined","includes","processPlaceholder","formatCurrency","code","renderUserContent","renderChatContent","map","user","filter","renderMessageContent","renderProductContent","renderMigratedContent","trim","renderGroupCallContent","invoice","getMessageSummaryText","messageSummary","renderMessageSummary","trimText","getUserFullName","renderText","chat","getChatTitle","placeholder","replaceValue","placeholderPosition","substring","Array","isArray","forEach","index","renderMessageText","highlight","shouldRenderHqEmoji","isSimple","truncateLength","entities","contentNotSupportedText","getMessageText","renderTextWithEntities","noEmoji","TRUNCATED_SUMMARY_LENGTH","hasSpoilers","some","emoji","getMessageSummaryEmoji","emojiWithSpace","description","getMessageSummaryDescription","RE_LETTER_OR_DIGIT","SIMPLE_MARKDOWN_REGEX","part","filters","params","compact","reduce","escapeHtml","EMOJI_REGEX","replaceEmojis","addLineBreaks","addHighlight","addLinks","replaceSimpleMarkdown","textParts","divEl","createElement","result","innerText","innerHTML","size","IS_EMOJI_SUPPORTED","parts","fixNonStandardEmoji","emojis","emojiResult","nativeToUnified","removeVS16s","src","alt","splittenParts","line","source","trimmedLine","trimLeft","indentLength","repeat","lowerCaseText","toLowerCase","queryPosition","nextSymbol","newParts","RE_LINK","RE_LINK_TEMPLATE","RE_MENTION_TEMPLATE","links","nextLink","shift","lastIndex","startsWith","username","endsWith","entityResult","entity","actionsByMessageId","createClassNameBuilder","contentRef","useRef","isRevealed","reveal","conceal","useFlag","stopPropagation","actions","contentLength","current","readingMs","round","timeoutMs","max","min","useEffect","has","ref","shouldRenderAsHtml","renderMessagePart","deleteLineBreakAfterPre","organizedEntities","organizedEntityIndexes","Set","organizedEntity","organizeEntity","organizedIndexes","organizedIndex","add","organizeEntities","renderEntity","textPartStart","textPartEnd","isLastEntity","renderResult","nestedEntities","offset","textBefore","textBeforeLength","substr","entityStartIndex","entityEndIndex","entityContent","nestedEntityContent","nestedIndex","nestedEntity","nestedEntityIndex","nestedResult","nestedEntityEndIndex","newEntity","rawEntityText","renderedContent","userId","getLinkUrl","processEntityAsHtml","entityText","renderNestedMessagePart","handleBotCommandClick","handleHashtagClick","handleCodeClick","role","tabIndex","MentionLink","SafeLink","processEntity","textAfter","arrayIndex","getTextWithEntitiesAsHtml","formattedText","c","concat","parsedEntity","isChanged","sendBotCommand","command","currentTarget","setLocalTextSearchQuery","query","searchTextMessagesLocal","copyTextToClipboard","showNotification","getTranslation","preventMessageInputBlur","withBubbling","IS_IOS","activeElement","EDITABLE_INPUT_ID","preventMessageInputBlurWithBubbling","withGlobal","global","userOrChat","selectUser","openChatByUsername","onContextMenu","onMouseDown","onMouseEnter","onMouseLeave","onFocus","color","backgroundImage","pill","fluid","isText","isLoading","ariaLabel","ariaControls","hasPopup","download","disabled","ripple","faded","withClickPropagation","elementRef","isClicked","setIsClicked","useState","fullClassName","handleMouseDown","style","label","subLabel","checked","blocking","onChange","onCheck","useLang","handleChange","event","trigger","positionX","positionY","footer","forceOpen","onOpen","onClose","menuRef","dropdownRef","isOpen","setIsOpen","onKeyDown","menu","keyCode","focusedElement","elementChildren","from","focus","onTrigger","containerRef","autoClose","shouldSkipTransition","success","readOnly","autoComplete","inputMode","maxLength","onInput","onKeyPress","onBlur","onPaste","labelText","htmlFor","backgroundColor","bubbleStyle","ariaLabelledBy","transformOriginX","transformOriginY","noCloseOnBackdrop","noCompact","onCloseAnimationEnd","backdropContainerRef","transitionClassNames","useShowTransition","captureEscKeyListener","useHistoryBack","useEffectWithPrevDeps","prevIsOpen","dispatchHeavyAnimationEvent","handleKeyDown","useKeyboardListNavigation","useVirtualBackdrop","bubbleClassName","transformOriginYStyle","transformOriginXStyle","IS_COMPACT_MENU","IS_BACKDROP_BLUR_SUPPORTED","props","icon","destructive","origin","ripples","setRipples","cleanUpDebounced","useMemo","debounce","button","container","position","getBoundingClientRect","rippleSize","offsetWidth","x","clientX","y","clientY","requestAnimationFrame","APP_NAME","APP_VERSION","process","DEBUG_MORE","IS_TEST","DEBUG_ALERT_MSG","PAGE_TITLE","INACTIVE_MARKER","DEBUG_PAYMENT_SMART_GLOCAL","SESSION_USER_KEY","LEGACY_SESSION_KEY","GLOBAL_STATE_CACHE_DISABLED","GLOBAL_STATE_CACHE_KEY","GLOBAL_STATE_CACHE_USER_LIST_LIMIT","GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT","GLOBAL_STATE_CACHE_CHATS_WITH_MESSAGES_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","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","CUSTOM_APPENDIX_ATTRIBUTE","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","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","STICKER_SIZE_JOIN_REQUESTS","STICKER_SIZE_INVITES","NO_STICKER_SET_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","GROUP_CALL_VOLUME_MULTIPLIER","GROUP_CALL_DEFAULT_VOLUME","ENABLE_THUMBNAIL_VIDEO","addActionHandler","importLegacySession","clearLegacySessions","apiUpdate","userAgent","navigator","PLATFORM_ENV","sessionData","loadStoredSession","isTest","search","isMovSupported","IS_MOV_SUPPORTED","isWebmSupported","IS_WEBM_SUPPORTED","phoneNumber","authIsLoading","authError","password","file","firstName","lastName","authIsLoadingQrCode","storeSession","currentUserId","clearStoredSession","_global","_actions","unsubscribe","forceWebsync","reset","forceInitApi","cacheApi","langCachePrefix","langCacheVersion","updateAppBadge","init","connectionState","authNearestCountry","getGlobal","deviceToken","subscribedAt","buildInputPrivacyRules","visibility","allowedIds","deniedIds","users","byId","usersById","chats","chatsById","rules","collectUsers","isUserId","collectChats","allowedUsers","allowedChats","blockedUsers","blockedChats","photo","bio","about","setGlobal","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","hash","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","appConfig","selectNotifySettings","setLanguage","onUpdateApiReady","wasAuthReady","authState","authorizationState","isLoggingOut","authIsCodeViaApp","isCodeViaApp","authHint","hint","authQrCode","qrCode","onUpdateAuthorizationState","onUpdateAuthorizationError","isOnAuth","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","setAttribute","toString","body","classList","IS_TOUCH_ENV","ensurePermanentWebVersion","startWebsync","IS_ANDROID","IS_MAC_OS","IS_SAFARI","uiReadyState","remove","authPhoneNumber","shouldSkipHistoryAnimations","forceSyncOnIOs","replaceThemeSettings","FOREVER_BANNED_DATE","VERIFIED_PRIORITY_BASE","PINNED_PRIORITY_BASE","entityId","isChatGroup","isChatBasicGroup","isChatSuperGroup","isChatChannel","isCommonBoxChat","isChatWithRepliesBot","getChatTypeString","getPrivateChatUserId","isSelf","getChatDescription","getChatLink","inviteLink","getChatAvatarHash","owner","avatarHash","isChatSummaryOnly","lastMessage","isChatAdmin","adminRights","getHasAdminRight","key","isUserRightBanned","currentUserBannedRights","defaultBannedRights","getCanPostInChat","threadId","isRestricted","migratedTo","isNotJoined","isCreator","getAllowedAttachmentOptions","isChatWithBot","canAttachMedia","canAttachPolls","canSendStickers","canSendGifs","canAttachEmbedLinks","isAdmin","getMessageSendingRestrictionReason","sendMessages","untilDate","formatDateToString","formatTime","getChatSlowModeOptions","slowMode","isChatArchived","folderId","selectIsChatMuted","notifySettings","notifyExceptions","isMuted","hasPrivateChatsNotifications","hasBroadcastNotifications","hasGroupNotifications","selectShouldShowMessagePreview","hasPrivateChatsMessagePreview","hasBroadcastMessagePreview","hasGroupMessagePreview","getCanDeleteChat","getFolderDescriptionText","folder","chatsCount","emoticon","pinnedChatIds","excludedChatIds","includedChatIds","excludeArchived","excludeMuted","excludeRead","values","bots","groups","channels","contacts","nonContacts","getMessageSenderName","getUserFirstOrLastName","sortChatIds","chatIds","shouldPrioritizeVerified","priorityIds","orderBy","priority","date","isVerified","filterChatsByName","searchWords","prepareSearchWordsForNeedle","getMessageHtmlId","getMessageKey","msgId","buildMessageKey","parseMessageKey","Number","getMessageOriginalId","previousLocalId","sticker","video","audio","voice","poll","webPage","contact","getMessageCustomShape","isRound","parseEmojiOnlyString","getMessageSingleEmoji","getFirstLinkInMessage","link","find","isOwnMessage","isOutgoing","isReplyMessage","replyToMessageId","isForwardedMessage","forwardInfo","isActionMessage","isServiceNotificationMessage","isAnonymousOwnMessage","senderId","getSenderTitle","getSendingState","sendingState","isMessageLocal","isHistoryClearMessage","getMessageContentFilename","isLottie","isVideo","isWebpSupported","baseFilename","IS_OPUS_SUPPORTED","areReactionsEmpty","reactions","results","l","count","isGeoLiveExpired","timestamp","period","getMessageRecentReaction","recentReactions","checkIfReactionAdded","oldReactions","newReactions","every","reaction","oldReactionsMap","acc","r","SPOILER_CHARS","noReactions","isExtended","getMessageTextWithSpoilers","accText","spoiler","fill","random","generateBrailleSpoiler","groupedId","truncatedText","summary","isGif","getMessageAudioCaption","question","performer","getMessageContent","hasMessageMedia","getMessagePhoto","getMessageVideo","getMessageDocument","getMessageSticker","getMessageContact","getMessagePoll","getMessageAction","getMessageAudio","getMessageVoice","getMessageRoundVideo","isMessageDocumentPhoto","mediaType","isMessageDocumentVideo","getMessageInvoice","getMessageLocation","getMessageWebPage","getMessageWebPagePhoto","getMessageWebPageVideo","getMessageMediaThumbDataUri","media","getMessageMediaThumbnail","dataUri","buildStaticMapHash","geo","width","height","zoom","scale","long","lat","accuracyRadius","getMessageMediaHash","webPagePhoto","webPageVideo","messageVideo","messagePhoto","mediaId","hasMessageLocalBlobUrl","getVideoOrAudioBaseHash","getAudioHasCover","IS_PROGRESSIVE_SUPPORTED","thumbnailSizes","getMessageMediaFormat","fullVideo","getMessageFileName","getMessageFileSize","blobUrl","getChatMediaMessageIds","messages","listedIds","isFromSharedMedia","getMessageContentIds","getPhotoFullDimensions","sizes","getPhotoInlineDimensions","getVideoDimensions","getMediaTransferState","isLoadNeeded","isUploading","isTransferring","transferProgress","messageIds","contentType","validator","matchLinkInMessageText","getMediaDuration","duration","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","isContact","sortUserIds","userIds","userStatusesById","getServerTime","expires","filterUsersByName","savedMessagesLang","getUserIdDividend","abs","getUserColorKey","peer","typed","typify","replaceChatListIds","newIds","listIds","updateChatListIds","idsUpdate","replaceChats","newById","updateChat","chatUpdate","updatedChat","getUpdatedChat","updatedById","keys","addChats","isUpdated","addedById","isMin","shouldOmitMinInfo","omit","photos","updateChatListType","listType","currentListIds","listTypeKey","currentFolderList","updateChatListSecondaryInfo","info","totalCountKey","orderedPinnedIds","totalChatCount","isFullyLoaded","leaveChat","leftChatId","selectChatListType","listId","addChatMembers","membersToAdd","currentMembers","members","newMemberIds","m","updatedMembers","currentIds","updatedIds","areSortedArraysEqual","updateStickerSets","category","sets","resultIds","updatedSets","stickerSet","existing","stickers","setsById","setIds","updateStickerSet","stickerSetId","currentStickerSet","addedSets","added","installedDate","updateGifSearch","isNew","nextOffset","currentResults","gifs","newResults","gif","replaceAnimatedEmojis","animatedEmojis","updateStickersForEmoji","remoteStickers","allStickers","selectStickersForEmoji","uniqueIds","unique","forEmoji","rebuildStickersForEmoji","replaceUsers","updateContactList","updatedUsers","contactUserIds","contactList","newContactUserIds","userUpdate","updatedUser","getUpdatedUser","updateUsers","deleteContact","MEMO_EMPTY_ARRAY","updateUserSearch","searchStatePartial","userSearch","updateUserSearchFetchingStatus","newState","fetchingStatus","updateUserBlockedState","isBlocked","replaceUserStatuses","statusesById","addUserStatuses","newKeys","pick","closeNewContactDialog","newContact","getComplexKey","updateGlobalSearch","globalSearch","updateGlobalSearchContent","currentContent","updateGlobalSearchResults","newFoundMessages","nextRate","resultsByType","newFoundMessagesById","foundIdsForType","foundIds","newId","updateGlobalSearchFetchingStatus","prevFoundIds","newFoundIds","prototype","foundOrPrevFoundIds","nextOffsetId","replaceLocalTextSearch","chatThreadKey","searchParams","localTextSearch","byChatThreadKey","updateLocalTextSearch","isActive","replaceLocalTextSearchResults","updateLocalTextSearchResults","orderFoundIds","replaceLocalMediaSearch","localMediaSearch","byChatId","updateLocalMediaSearchType","currentType","updateLocalMediaSearchResults","replaceLocalMediaSearchResults","sort","a","b","updateManagementProgress","management","updateManagement","newSettings","themes","notifyException","exceptionData","addNotifyException","updateTwoFaSettings","twoFaSettings","updateShippingOptions","shippingOptions","payment","setRequestInfoId","requestId","setPaymentStep","step","setInvoiceMessageInfo","photoUrl","invoiceContent","setStripeCardInfo","cardInfo","stripeCredentials","setSmartGlocalCardInfo","smartGlocalCredentials","setPaymentForm","form","setConfirmPaymentUrl","confirmPaymentUrl","setReceipt","receipt","messageInvoice","clearPayment","closeInvoice","isPaymentModalOpen","updateStatistics","statistics","updateStatisticsGraph","updateCurrentMessageList","shouldReplaceHistory","messageLists","newMessageLists","last","replaceChatMessages","updateMessageStore","updateThread","threadUpdate","threadsById","replaceThreadParam","paramName","newValue","addMessages","addedByChatId","messagesByChatId","addChatMessagesById","selectChatMessages","updateChatMessage","messageUpdate","updatedMessage","updateScheduledMessage","selectScheduledMessages","replaceScheduledMessages","deleteChatMessages","deletedForwardedPosts","pickTruthy","isLinkedChannelPost","threadInfo","selectThreadInfo","selectListedIds","outlyingIds","selectOutlyingIds","viewportIds","selectViewportIds","pinnedIds","selectPinnedIds","newMessageCount","messagesCount","currentMessageList","selectCurrentMessageList","canDeleteCurrentThread","currentThreadId","fromChatId","fromMessageId","originalPost","selectChatMessage","deleteChatScheduledMessages","scheduledIds","selectScheduledIds","updateListedIds","orderHistoryIds","updateOutlyingIds","addViewportId","safeReplaceViewportIds","newViewportIds","updateThreadInfo","newThreadInfo","updateThreadInfos","updates","scheduledMessages","updateScheduledMessages","updateFocusedMessage","noHighlight","isResizingContainer","focusedMessage","updateSponsoredMessage","sponsoredByChatId","updateFocusDirection","direction","enterMessageSelectMode","selectedMessages","toggleMessageSelection","messageListType","childMessageIds","withShift","oldSelectedMessages","selectMessageIdsByGroupId","selectedMessageIds","newMessageIds","newSelectedMessageIds","selectCurrentMessageIds","prevIndex","currentIndex","to","exitMessageSelectMode","updateThreadUnreadFromForwardedMessage","originMessage","lastMessageId","isDeleting","channelPostId","threadInfoOld","selectChat","selectIsChatWithSelf","selectIsChatWithBot","selectChatUser","selectSupportChat","isSupport","selectChatOnlineCount","onlineCount","selectChatBot","selectIsChatBotNotStarted","bot","messageInfo","selectAreActiveChatsLoaded","active","selectIsChatListed","targetList","list","selectChatFolder","chatFolders","selectIsChatPinned","archived","chatFoldersById","selectChatByUsername","usernameLowered","selectIsServiceChatReady","selectSendAs","sendAsId","selectCurrentStickerSearch","selectCurrentGifSearch","selectStickerSet","selectStickerSetByShortName","shortName","stickerSets","stickersForEmoji","favorite","packs","cleanEmoji","selectAnimatedEmoji","cleanedEmoji","selectAnimatedEmojiEffect","animatedEmojiEffects","selectAnimatedEmojiSound","emojiSounds","selectLocalAnimatedEmoji","selectLocalAnimatedEmojiEffect","selectLocalAnimatedEmojiEffectByName","selectCurrentChat","selectThreadParam","thread","selectScrollOffset","selectReplyingToId","selectEditingId","selectEditingDraft","selectEditingScheduledId","selectEditingScheduledDraft","selectDraft","selectNoWebPage","selectFirstMessageId","selectReplyStack","selectThreadOriginChat","originChannelId","selectThreadTopMessageId","topMessageId","selectThreadByMessage","replyToTopMessageId","selectIsMessageInCurrentMessageList","selectIsViewportNewest","chatMessages","selectScheduledMessage","selectEditingMessage","selectChatMessageByPollId","pollId","messageWithPoll","selectFocusedMessageId","focusedChatId","selectIsMessageFocused","focusedId","selectIsMessageUnread","lastReadOutboxMessageId","selectOutgoingStatus","isScheduledList","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","canSaveGif","noOptions","ability","selectCanDeleteSelectedMessages","messageActions","selectCanReportSelectedMessages","selectCanDownloadSelectedMessages","selectIsDownloading","activeInChat","activeDownloads","selectActiveDownloadIds","selectUploadProgress","fileUploads","byMessageLocalId","selectRealLastReadId","lastReadInboxMessageId","Infinity","selectFirstUnreadId","lastReadId","lastReadServiceNotificationId","serviceNotifications","notification","isUnread","findAfterLastReadId","isFromScheduled","found","selectIsForwardModalOpen","forwardMessages","isModalShown","selectCommonBoxChatId","fromLastMessage","selectIsInSelectMode","selectIsMessageSelected","selectForwardedMessageIdsByGroupId","selectIsDocumentGroupSelected","selectedIds","groupIds","selectSelectedMessagesCount","selectNewestMessageWithBotKeyboardButtons","findLast","keyboardButtons","replyHideMessageId","shouldHideKeyboardButtons","selectCanAutoLoadMedia","isPhoto","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","selectDefaultReaction","defaultReaction","availableReactions","isInactive","enabledReactions","selectVisibleUsers","selectShouldSchedule","selectCanScheduleUntilOnline","chatBot","selectUserStatus","selectCurrentTextSearch","currentSearch","selectCurrentMediaSearch","selectStatistics","selectManagement","selectCurrentManagementType","selectIsMediaViewerOpen","mediaViewer","avatarOwnerId","selectRightColumnContentKey","pollResults","selectIsPollResultsOpen","RightColumnContent","IS_SINGLE_COLUMN_LAYOUT","currentManagement","selectCurrentManagement","isStatisticsShown","currentChatId","canViewStatistics","selectIsStatisticsShown","newChatMembersProgress","NewChatMembersProgress","isChatInfoShown","selectIsRightColumnShown","shouldUseSystemTheme","getSystemTheme","selectCurrentGlobalSearchQuery","selectPaymentChatId","selectPaymentMessageId","selectPaymentFormId","formId","selectPaymentRequestId","selectProviderPublishableKey","nativeParams","publishableKey","selectProviderPublicToken","publicToken","selectStripeCredentials","selectSmartGlocalCredentials","selectNotifyExceptions","selectIsUserBlocked","selectUserByPhoneNumber","phoneNumberCleaned","cb","dependencies","debugKey","prevDeps","usePrevious","initial","setValue","setTrue","setFalse","setTrigger","ANIMATION_START_EVENT","ANIMATION_END_EVENT","timeout","isAnimating","isHeavyAnimating","onEnd","clearTimeout","dispatchEvent","Event","handleAnimationStart","handleAnimationEnd","isDisabled","removeEventListener","LOCATION_HASH","PATH_BASE","pathname","historyState","nextStateIndexToReplace","isHistoryAltered","isEdge","currentIndexes","disableHistoryBack","handleTouchEnd","onBack","onForward","currentState","shouldReplaceNext","hashes","indexRef","isForward","prevIsActive","isClosed","indexHashRef","prevHashes","isHashChangedFromEvent","isForceClose","prev","history","pushState","state","realDelta","indexLast","findIndex","go","replaceState","back","handlePopState","currIndex","disableHistoryAnimations","hasChanged","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","d","next","shouldSkipUndefined","onCloseTransitionEnd","noOpenTransition","noCloseTransition","setIsClosed","closeTimeoutRef","hasOpenClassName","setHasOpenClassName","exec","shouldHaveOpenClassName","isClosing","shouldRender","handleEvent","contains","NON_BUBBLEABLE_EVENTS","documentEventCounters","delegationRegistryByEventType","delegatedEventTypesByElement","propName","handler","asCapture","eventType","resolveEventType","canUseEventDelegation","addDelegatedListener","removeDelegatedListener","tagName","realEventType","resolveDelegationRegistry","newSet","resolveDelegatedEventTypes","removeAllDelegatedListeners","eventTypes","realEvent","events","furtherCallsPrevented","Proxy","p","Reflect","parentNode","documentListenersCount","delegatedHandlersCount1","counter","delegationRegistriesCount","delegatedHandlersCount2","delegationRegistry","delegationElementsCount","delegatedEventTypesCount","FILTERED_ATTRIBUTES","HTML_ATTRIBUTES","MAPPED_ATTRIBUTES","autoPlay","headsByElement","renderWithVirtual","parentEl","$current","$new","$parent","skipComponentUpdate","forceIndex","fragment","moveDirection","isCurrentComponent","isComponentElement","isNewComponent","hasElementChanged","updateComponent","componentInstance","isMounted","setupComponentUpdateListener","newTarget","getTarget","initComponent","node","createNode","setTarget","childNodes","insertBefore","appendChild","removeChild","unmountTree","replaceChild","areComponents","isRealElement","nextSibling","updateAttributes","renderChildren","$element","mountComponent","$firstChild","renderComponent","isEmptyElement","createTextNode","isTextElement","tag","entries","$child","currentEl","firstChild","child","DEBUG_checkKeyUniqueness","teactFastList","$newChild","currentRemainingIndex","remainingByKey","$currentChild","isKeyPresent","newChildKey","order","teactOrderKey","fragmentQueue","fragmentIndex","newChildren","currentPreservedIndex","currentChildInfo","flushFragmentQueue","shouldMoveNode","isMovingDown","renderFastListChildren","currentChildrenLength","newChildrenLength","createDocumentFragment","$fragmentChild","currentEntries","newEntries","currentValue","cssText","removeAttribute","__html","render","headId","getAttribute","$head","VirtualElementTypesEnum","Fragment","Symbol","DEBUG_SILENT_RENDERS_FOR","renderingInstance","Empty","Text","isTagElement","Tag","Component","flatten","createComponentInstance","buildTagElement","parsedChildren","hooks","cursor","byCursor","effects","memos","buildComponentElement","dropEmptyTail","buildChildElement","isEmptyPlaceholder","DEBUG_components","newRenderedValue","DEBUG_startAt","componentName","renderCount","renderTimes","performance","handleError","renderedValue","newChild","$old","memoContainer","cleanup","hook","effect","nextValue","setter","helpGc","prepareComponentForFrame","prepareForFrame","throttleWithPrimaryRaf","throttleWithRaf","forceUpdateComponent","currentElement","componentElement","DEBUG_contentComponentName","useLayoutEffectBase","schedulerFn","primarySchedulerFn","execCleanup","dependency","causedBy","res","prevValue","fastRaf","fastRafPrimary","useLayoutEffect","onTickEnd","onTickEndPrimary","resolver","getUnequalProps","newCallback","currentGlobal","actionHandlers","callbacks","containers","mapStateToProps","ownProps","mappedProps","newMappedProps","isNaN","DEBUG_componentName","arePropsShallowEqual","areMappedPropsChanged","DEBUG_updates","updateTime","runCallbacksThrottled","throttleWithTickEnd","runCallbacks","forceOnHeavyAnimation","newGlobal","handleAction","addCallback","removeCallback","TeactNContainer","vs16RegExp","zeroWidthJoiner","rawEmoji","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","unreadCount","setAppBadge","currentProps","newProps","currentKeys","currentKeysLength","prop","elementName","baseName","modifiers","modifier","self","caches","Type","fetch","cacheName","isHtmlAllowed","request","Request","cache","open","headers","Blob","blob","shouldRecreate","resolvedType","Json","json","save","cacheData","Response","put","clear","createCallbackManager","hasCallbacks","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","CLIPBOARD_ITEM_SUPPORTED","clipboard","ClipboardItem","textCopyEl","str","selection","getSelection","rangeToRestore","rangeCount","getRangeAt","select","execCommand","removeAllRanges","addRange","copyImageToClipboard","imageUrl","canvas","ctx","getContext","imageEl","Image","onload","img","drawImage","toBlob","copyBlobToClipboard","pngBlob","write","WEEKDAYS_FULL","MONTHS_FULL","MONTHS_FULL_LOWERCASE","month","MILLISECONDS_IN_DAY","isToday","getDayStartAt","getDayStart","datetime","toYearMonth","getFullYear","getMonth","toIsoString","hours","getHours","marker","padStart","getMinutes","formatPastTimeShort","weekAgo","getDay","withYear","format","formatDate","formatMonthAndYear","isShort","formatCountdown","msLeft","days","formatMediaDuration","formatCountdownShort","ceil","formatLastUpdated","currentTime","lastUpdated","seconds","formatHumanDate","noWeekdays","isUpperFirst","upperFirst","lowerFirst","weekAhead","weekDay","formatKey","day","monthIndex","formatMediaDateTime","maxValue","minutes","maxHours","maxMinutes","string","formatVoiceRecordDuration","durationInMs","milliseconds","formatDayToStringWithCache","withCache","dayStartAt","locale","toLocaleString","year","formatDateTimeToString","hour","minute","second","isValidDate","MAX_MONTH_IN_YEAR","parseDateString","matchStringDate","matchEuropeStringDate","matchNumberDate","dateParts","timestampPlusDay","EXCLUDE_EMOJIS","EMOJI_EXCEPTIONS","unifiedToNative","unified","codePoints","parseInt","fromCodePoint","regex","replacement","pairs","uncompressEmoji","emojiData","categories","emojiRaw","names","native","image","isoToEmoji","iso","test","codePointAt","isWebpSupportedCache","webp","handleLoadOrError","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","IS_REQUEST_FULLSCREEN_SUPPORTED","ARE_CALLS_SUPPORTED","LAYERS_ANIMATION_NAME","TEST_VIDEO","DPR","devicePixelRatio","MASK_IMAGE_DISABLED","CSS","supports","IS_SCROLL_PATCH_NEEDED","MESSAGE_LIST_SENSITIVE_AREA","dataUriToBlob","arr","mime","bstr","atob","u8arr","Uint8Array","blobToDataUri","reader","FileReader","readAsDataURL","blobToFile","File","lastModified","preloadImage","preloadVideo","volume","onloadedmetadata","createPosterForVideo","onseeked","videoWidth","videoHeight","toDataURL","fetchBlob","fetchFile","imgToCanvas","constructor","fileBits","rest","super","this","initials","buildInitials","prevGlobal","prepared","updateFolderManagerThrottled","throttle","onIdle","updateFolderManager","inited","getOrderedIds","orderedIdsByFolderId","getPinnedChatsCount","pinnedCountByFolderId","getChatsCount","chatsCountByFolderId","getUnreadCounters","unreadCountersByFolderId","getAllNotificationsCount","notificationsCount","addOrderedIdsCallback","addChatsCountCallback","addUnreadCountersCallback","DEBUG_startedAt","isAllFolderChanged","isMainFolderChanged","isArchivedFolderChanged","isAllFullyLoadedChanged","isAllFolderFullyLoaded","isArchivedFullyLoadedChanged","isArchivedFolderFullyLoaded","areFoldersChanged","foldersById","areChatsChanged","areUsersChanged","areNotifySettingsChanged","areNotifyExceptionsChanged","affectedFolderIds","emptyFolderIds","folderSummariesById","updateFullyLoaded","updateResults","prevAllFolderListIds","allFolderListIds","prevArchivedFolderListIds","archivedFolderListIds","changedFolders","newListIds","newPinnedIds","buildFolderSummaryFromMainList","allFolderPinnedIds","archivedFolderPinnedIds","newFoldersById","buildFolderSummary","updateFolders","newChatsById","newUsersById","newNotifySettings","newNotifyExceptions","folderSummaries","newAllFolderListIds","newArchivedFolderListIds","allIds","newFolderIds","currentSummary","chatSummariesById","newSummary","unreadMentionsCount","hasUnreadMark","joinDate","draftDate","userInfo","isListed","isArchived","isUserContact","buildChatSummary","chatSummary","folderSummary","isChatInFolder","buildChatFolderIds","currentFolderIds","folderIdsByChatId","deletedFolderIds","currentFolderIdsSet","newFolderIdsSet","currentFolderOrderedIds","chatIdsByFolderId","isOrderedListJustPatched","updateListsForChat","currentPinnedIds","wasUnreadCountersChanged","wasChatsCountChanged","pinnedCount","newPinnedCount","orderedIds","newOrderedIds","prevOrderedIds","sortedPinnedIds","allListIds","sortedNotPinnedIds","chatId1","chatId2","buildFolderOrderedIds","currentOrderedIds","currentPinnedCount","currentChatsCount","newChatsCount","currentUnreadCounters","newUnreadCounters","buildFolderUnreadCounters","newInitials","totalPrice","Intl","NumberFormat","store","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","BOT_PRECHECKOUT_TIMEOUT","SHIPPING_ERRORS","getReadableErrorText","isSlowMode","textParams","extraPartIndex","errorMessage","handleErrorEvent","ErrorEvent","reason","alert","collection","member","mapValues","newByKey","object","stringKeys","orderRule","mode","compareValues","currentOrderRule","isAsc","aValue","bValue","mode1","mode2","orderRule1","orderRule2","isAsc1","isAsc2","array","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","currentLangCode","currentTimeFormat","cacheValue","cached","langString","processTranslation","importFallbackLangPack","getTranslationForLangString","translateString","remoteLangPack","remote","fetchRemoteString","withFallback","newLangPack","fetchRemote","langInfo","rtl","default","sourceLangPacks","template","optionIndex","getPluralOption","translationSlices","initialValue","processTemplate","formatInteger","SAMPLE_RATE","oggToWav","opusData","arrayBuffer","typedArray","decoderWorker","wavWorker","onmessage","buffers","buffer","page","terminate","wavBitDepth","wavSampleRate","decoderSampleRate","outputBufferSampleRate","pages","asCacheApiType","memoryCache","fetchPromises","progressCallbacks","cancellableCallbacks","mediaFormat","onProgress","callbackUniqueId","getProgressive","fetchFromCacheOrRemote","activeCallbacks","getFromMemory","cancelProgress","parentCallback","progressiveUrl","mediaPng","webpToPng","prepareMedia","mediaSource","MediaSource","streamUrl","sourceBuffer","addSourceBuffer","makeOnProgress","revokeObjectURL","endOfStream","appendBuffer","mediaData","serviceWorker","fullSize","controller","Bundles","LOAD_PROMISES","MEMORY_CACHE","Auth","Main","Extra","Calls","bundle","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","notifyAboutMessage","isReaction","resultSettings","resultExceptions","loadNotificationSettings","hasFocus","checkIfShouldNotify","areNotificationsSupported","activeReaction","imageHash","mediaLoader","getAvatar","messageSender","messageAction","actionTargetMessage","targetUserIds","actionTargetUserIds","actionTargetChatId","actionTargetUsers","privateChatUserId","privateChatUser","isChat","senderName","getNotificationContent","badge","vibrate","onclick","close","startActiveReaction","onshow","closeMessageNotifications","notifyClientReady","PERMANENT_VERSION_KEY","AVAILABLE_VERSIONS","setPermanentWebVersion","version","hasPermanentWebVersion","PATTERN_PLACEHOLDER","DEFAULT_PATTERN","getCountryCodesByIso","phoneCodeList","country","iso2","getCountryFromPhoneNumber","possibleCountries","countryCode","codesWithPrefix","prefixes","prefix","bestMatches","formatPhoneNumber","pattern","numberWithoutCode","patterns","defaultPattern","stripped","getBestPattern","formatPhoneNumberWithCode","numberWithPlus","createMessageHash","messageList","typeOrThreadId","parseLocationHash","isType","fn","waitingTimeout","shouldRunFirst","shouldRunLast","interval","isPending","_args","setInterval","clearInterval","throttleWith","waiting","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","tryIdb","intervalId","onupgradeneeded","createObjectStore","txMode","db","transaction","objectStore","createStore","DC_IDS","hasStoredSession","withLegacy","userAuthJson","dcID","dcId","removeItem","sessionId","sessionJson","customStore","idb","idbKeys","getAllKeys","items","openCursor","continue","eachCursor","isInitialized","HEX_COLOR_REGEX","RGB_VARIABLES","lerp","start","end","interpolationRatio","colors","themeColors","property","hexToRgb","hex","g","applyColorAnimationStep","startIndex","endIndex","propertyColors","withAnimation","isDarkTheme","shouldAnimate","startAt","themeColorTag","querySelector","transition","formatFixedNumber","formatIntegerCompact","views","getFirstLetters","phrase","word","EMPTY_IMAGE_DATA_URI","initWebpWorker","wasmReady","requests","getDecodePromise","ImageData","putImageData","createPng","webpToPngBase64","handleLibWebpMessage","WEBSYNC_URLS","WEBSYNC_VERSION","WEBSYNC_KEY","getTs","lastTimeout","authed","currentTs","canRedirect","ts","script","removeElement","URLSearchParams","saveSync","clearWebsync","IS_LANDSCAPE","isLandscape","initialHeight","currentWindowSize","updateSizes","isRefreshDisabled","handleResize","visualViewport","pageTop","vh","getIsKeyboardVisible","disableRefresh","enableRefresh","WeakMap","fnCache","cacheKey","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","exports","__webpack_modules__","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","registrations","getRegistrations","unregister","register","hasErrorKey","INITIAL_STATE","isLeftColumnShown","phoneCodes","general","groupCalls","activeChatFolder","recentEmojis","recent","greeting","featured","emojiKeywords","saved","inlineBots","byUsername","topPeers","topInlineBots","playbackRate","audioPlayer","notifications","dialogs","messageSendKeyCombo","autoLoadFileMaxSizeMb","shouldSuggestStickers","isConnectionStatusMinimized","light","isBlurred","patternColor","dark","activeReactions","shouldShowContextMenuHint","updateCacheThrottled","updateCache","unsubscribeFromBeforeUnload","isCaching","setupCaching","clearCaching","reducedGlobal","reduceShowChatInfo","reduceUsers","reduceChats","reduceMessages","recentlyFoundChatIds","reduceSettings","reduceChatFolders","reduceGroupCalls","reduceAvailableReactions","visibleUserIds","idsToSave","currentChat","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","reactionThumbsPath","telegramLogoPath","authCode","monkeyPath","authPassword","background","hasCustomBackground","hasCustomBackgroundColor","isRightColumnShown","leftColumnWidth","setIsUiReady","isReady","markReady","shouldRenderMask","safePreload","translation","setTranslation","getSuggestedLanguage","suggestedLanguage","MENU_HIDING_DURATION","inputRef","setFilter","filteredList","setFilteredList","updateFilter","filterValue","defaultName","getFilteredList","prevPhoneCodeList","handleInput","handleInputKeyDown","CodeInput","handleTrigger","formEl","getElementById","scrollTo","top","scrollHeight","behavior","inputValue","Spinner","DropdownMenu","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","colorStops","createLinearGradient","apply","createRadialGradient","addColorStop","A","minVersion","maxVersion","ecLevel","radius","quiet","HTMLCanvasElement","clearRect","S","multiply","L","M","Q","returnToAuthPhoneNumber","qrCodeRef","token","isMobile","windowSize","AuthQrCode","appInactivePath","renderMain","disconnect","markInactive","TeactDOM"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/report.html b/dist/report.html index 7494936f..4f36aa4a 100644 --- a/dist/report.html +++ b/dist/report.html @@ -3,7 +3,7 @@ - telegram-t [19 Mar 2022 at 21:21] + telegram-t [20 Mar 2022 at 14:28]